简体   繁体   English

如何在 javascript 中找到二维对象数组的索引

[英]How can I find the index of a 2d array of objects in javascript

So, what I'm trying to get is the index of a 2d array of objects, let's say I have the following所以,我想要得到的是二维对象数组的索引,假设我有以下

const arr = [
  [{id: 1}, {id:2}],
  [{id:3},{id:4},{id:5}]
  ]

If I'd want to get the index where id=3 it would be arr[1][0] , Is there any way to achieve this using vanilla JS or any helper library?如果我想获得 id=3 的索引,它将是arr[1][0] ,有没有办法使用 vanilla JS 或任何辅助库来实现这一点?

Might be a more efficient way to do it, but you could accomplish this via array.findIndex :可能是一种更有效的方法,但您可以通过array.findIndex完成此操作:

 const test = [ [{id: 1}, {id:2}], [{id:3},{id:4},{id:5}] ]; function find(arr, id) { const firstIndex = arr.findIndex(entry => entry.some(({id: x}) => x === id)); if (firstIndex > -1) { const secondIndex = arr[firstIndex].findIndex(({ id: x }) => x === id ); return [firstIndex, secondIndex]; } } console.log(find(test, 2)); // [0, 1] console.log(find(test, 4)); // [1, 1] console.log(find(test, 5)); // [1, 2]

 const arr = [ [{id: 1}, {id:2}], [{id:3},{id:4},{id:5}] ]; let searchIndex = 3; let x = arr.findIndex(sub => sub.find(el => el.id == searchIndex)); let y = arr[x].findIndex(el => el.id == searchIndex); console.log(x, y)

You can achieve this by nesting two for loops.您可以通过嵌套两个 for 循环来实现这一点。

function findNestedIndices(array, id) {
  let i;
  let j;

  for (i = 0; i < array.length; ++i) {
    const nestedArray = array[i];
    for (j = 0; j < nestedArray.length; ++j) {
      const object = nestedArray[j];
      if (object.id === id) {
        return { i, j };
      }
    }
  }
  return {};
}
const array = [
  [{id: 1}, {id:2}],
  [{id:3},{id:4},{id:5}]
];

const { i, j } = findNestedIndices(array, 3);

console.log(i, j); // 1, 0

 const arr = [ [{id: 1}, {id:2}], [{id:3},{id:4},{id:5}] ]; function getIndex(arr, value){ let rowIndex = null; let valueIndex = null; arr.forEach(( nestedArray, index) => { if(;valueIndex) rowIndex = index. nestedArray,every((val. valIndex) => { if(val;id === value) { valueIndex = valIndex; return false } return true; }), }) return { rowIndex. valueIndex } } console,log(getIndex(arr, 3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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