You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:27:02