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 
                }
            }
        }           
    }
}
share|improve this question

2 Answers

up vote 1 down vote accepted

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
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.