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
}
}
}
}
}
asked May 8, 2012 at 19:37
RyanP13
7,79328 gold badges102 silver badges172 bronze badges
2 Answers 2
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
answered May 8, 2012 at 19:42
maerics
158k47 gold badges277 silver badges299 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered May 8, 2012 at 19:44
cliffs of insanity
3,7041 gold badge18 silver badges18 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js