Finding index of value in two dimensional array of objects in javascript
11,069
Solution 1
Wrap your code in a function, replace your comment with return i
, fallthrough by returning a sentinel value (e.g. -1):
function indexOfRowContainingId(id, matrix) {
for (var i=0, len=matrix.length; i<len; i++) {
for (var j=0, len2=matrix[i].length; j<len2; j++) {
if (matrix[i][j].id === id) { return i; }
}
}
return -1;
}
// ...
indexOfRowContainingId(222, arr); // => 1
indexOfRowContainingId('bogus', arr); // => -1
Solution 2
Since you know you want the id
, you don't need the for-in
loop.
Just break the outer loop, and i
will be your value.
var arr = [[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]],
len = arr.length
ID = 789;
OUTER: for (var i = 0; i < len; i++){
for (var j = 0; j < arr[i].length; j++){
if (arr[i][j].id === ID)
break OUTER;
}
}
Or make it into a function, and return i
.
Author by
RyanP13
Updated on June 04, 2022Comments
-
RyanP13 almost 2 years
I have a 2D array of objects like so:
[[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]]
I need to find the index of the id at the top array level.
So if i was to search for and id property with value '222' i would expect to return an index of 1.
I have tried the following:
var arr = [[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]], len = arr.length ID = 789; for (var i = 0; i < len; i++){ for (var j = 0; j < arr[i].length; j++){ for (var key in o) { if (key === 'id') { if (o[key] == ID) { // get index value } } } } }