I have an array of arrays like below.
array = [[false, 1, "label", "label value", null],[false, 2, "label1", "label1", null]]
I want to find the row matching to checkNum and return that row. checkNum is pared to the second index element. I don't want to put a for loop something like below,
checkNum = 1;
for (let i = 0; i < array.length; i++) {
if ((array[i][1]) === checkNum) {
}
}
I have an array of arrays like below.
array = [[false, 1, "label", "label value", null],[false, 2, "label1", "label1", null]]
I want to find the row matching to checkNum and return that row. checkNum is pared to the second index element. I don't want to put a for loop something like below,
checkNum = 1;
for (let i = 0; i < array.length; i++) {
if ((array[i][1]) === checkNum) {
}
}
Share
Improve this question
edited Apr 26, 2019 at 16:18
Slai
22.9k5 gold badges48 silver badges55 bronze badges
asked Apr 26, 2019 at 16:09
user1015388user1015388
1,5355 gold badges29 silver badges60 bronze badges
2
- do you have only one item in the array which match, or could there be more? – Nina Scholz Commented Apr 26, 2019 at 16:10
- array.filter((row) => row[1] === checkNum)[0] – karthick Commented Apr 26, 2019 at 16:11
2 Answers
Reset to default 4Use Array.filter()
to get an array of items that match the criteria, or Array.find()
the get the 1st item that matches.
const array = [[false, 1, "label", "label value", null],[false, 2, "label1", "label1", null]]
const checkNum = 1
console.log(array.filter(({ 1: n }) => n === checkNum)) // array of items
console.log(array.find(({ 1: n }) => n === checkNum)) // 1st item found
You could find the item with Array#find
.
var array = [[false, 1, "label", "label value", null], [false, 2, "label1", "label1", null]],
checkNum = 1,
result = array.find(a => a[1] === checkNum);
console.log(result);