5

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
0

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.