如何使用高阶函数在一个数组中查找另一个数组的索引?

4

我可以找出一个数组是否存在于另一个数组中:

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];

const match = [2,2,2];

// Does match exist
const exists = arr1.some(item => {
  return item.every((num, index) => {
    return match[index] === num;
  });
});

我可以找到该数组的索引:

let index;
// Index of match
for(let x = 0; x < arr1.length; x++) {
  let result;
  for(let y = 0; y < arr1[x].length; y++) {
    if(arr1[x][y] === match[y]) { 
      result = true; 
    } else { 
      result = false; 
      break; 
    }
  }
  
  if(result === true) { 
    index = x; 
    break;
  }
}

但是使用JS的高阶函数能否找到索引呢?我没有看到类似的问题/答案,语法方面更加简洁。

谢谢

2个回答

5
您可以使用 Array#findIndex 方法。

const
    array = [[1, 2, 3], [2, 2, 2], [3, 2, 1]],
    match = [2, 2, 2],
    index = array.findIndex(inner => inner.every((v, i) => match[i] === v));

console.log(index);


啊,太完美了,这正是我想要的组合。谢谢! - NickW

0
另一种方法是将数组的inner-arrays转换为字符串,例如['1,2,3','2,2,2','3,2,1'],并将匹配的数组也转换为字符串2,2,2。然后使用内置函数indexOf在数组中搜索该索引。

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];
const match = [2,2,2];

const arr1Str = arr1.map(innerArr=>innerArr.toString());
const index = arr1Str.indexOf(match.toString())
console.log(index);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接