简体   繁体   中英

Finding index of value in two dimensional array of objects in javascript

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 
                }
            }
        }           
    }
}

Wrap your code in a function, replace your comment with return i , fallthrough by returning a sentinel value (eg -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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM