JavaScript中查找二维数组X符合二维数组Y指定位置值的元素索引
实现方案
你之前的方案出错的核心原因是toString()+indexOf()的组合是模糊字符串匹配,会出现子串误判的问题,且findIndex()只能返回第一个匹配项的索引,无法收集所有符合条件的结果。直接做精确的数组元素位对比即可解决问题,时间复杂度为O(n),适配数百到数千条数据的场景完全无性能压力。
推荐实现(reduce 版本)
const X = [['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'g', 'c']]; const Y = [['a', 'x', 'c'], ['y', 'z', 'c']]; // 提前提取对比目标值,减少循环内的重复读取 const targetFirst = Y[0][0]; const targetThird = Y[0][2]; // 遍历收集所有匹配的索引 const matchedIndexes = X.reduce((resultList, currentItem, index) => { // 增加子数组长度判断,避免索引越界报错 if (currentItem.length >= 3 && currentItem[0] === targetFirst && currentItem[2] === targetThird) { resultList.push(index); } return resultList; }, []); console.log(matchedIndexes); // 示例输出:[0, 2]
兼容旧环境的for循环版本
const matchedIndexes = []; const targetFirst = Y[0][0]; const targetThird = Y[0][2]; for (let i = 0; i < X.length; i++) { const currentItem = X[i]; if (currentItem.length >= 3 && currentItem[0] === targetFirst && currentItem[2] === targetThird) { matchedIndexes.push(i); } }
说明
- 严格相等符
===会同时对比值和类型,不会出现SALES匹配到SALE的子串误判问题 - 提前提取
Y[0][0]和Y[0][2]可以避免循环中重复读取Y的嵌套属性,进一步提升性能 - 子数组长度判断可以避免X中存在长度不足3的子元素时抛出索引越界错误
内容的提问来源于stack exchange,提问作者Tojo Randrian
相关产品推荐
相关产品推荐

