如何使用JavaScript高阶函数查找嵌套数组中目标子数组的索引?
实现方案
可以直接使用JavaScript内置的Array.prototype.findIndex高阶方法完成需求,比双层for循环写法更简洁,逻辑可读性更强:
const arr1 = [[1,2,3],[2,2,2],[3,2,1]]; const match = [2,2,2]; // 找到第一个匹配的子数组索引,无匹配时返回-1 const matchedIndex = arr1.findIndex(item => { // 先校验长度一致避免误判,再逐位比对元素 return item.length === match.length && item.every((num, index) => num === match[index]); });
扩展场景:获取所有匹配的子数组索引
如果需要返回所有符合条件的子数组索引,可搭配map+filter实现:
const allMatchedIndexes = arr1 .map((item, index) => { return item.length === match.length && item.every((num, i) => num === match[i]) ? index : -1 }) .filter(index => index !== -1);
内容的提问来源于stack exchange,提问作者NickW
相关产品推荐
相关产品推荐

