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

如何在JavaScript数组中搜索指定值并返回包含数组索引与位置的新数组

在JavaScript嵌套数组中定位特定值的位置

没问题,我来帮你搞定这个需求——从嵌套数组里定位特定值的位置,还不用写普通循环,用JavaScript的数组高阶方法就能轻松实现,代码还简洁易读。

基础实现(每个内层数组仅一个匹配项)

如果能确定每个内层数组里最多只有一个目标值,用flatMap是最直观的选择:

const work = [
  [1985, 1987, 1990, 2000, 2010],
  [1984, 1998],
  [1975, 1986, 1987, 1990],
  [2001, 2010],
  [1977, 1978, 1990]
];

const targetYear = 1990;

// 使用flatMap收集匹配结果
const sorted = work.flatMap((innerArray, outerIndex) => {
  const innerPosition = innerArray.indexOf(targetYear);
  // 找到值就返回包含位置的数组,否则返回空数组(flatMap会自动忽略空数组)
  return innerPosition !== -1 ? [[outerIndex, innerPosition]] : [];
});

console.log(sorted);
// 输出: [[0, 2], [2, 3], [4, 2]]

代码说明

  • flatMap会遍历外层数组的每个元素(也就是每个内层数组),同时获取当前的外层索引。
  • 对每个内层数组,用indexOf查找目标值的位置:找到则返回包含[外层索引, 内层位置]的数组,没找到则返回空数组。
  • flatMap会自动将所有返回的数组合并成一个一维数组,正好符合你想要的结果格式。

扩展实现(支持内层数组多个匹配项)

如果某个内层数组里可能存在多个目标值(比如同一个数组里有多个1990),可以修改代码来收集所有匹配位置:

const sorted = work.flatMap((innerArray, outerIndex) => {
  const matches = [];
  let currentPosition = innerArray.indexOf(targetYear);
  
  // 循环查找所有匹配位置
  while (currentPosition !== -1) {
    matches.push([outerIndex, currentPosition]);
    currentPosition = innerArray.indexOf(targetYear, currentPosition + 1);
  }
  
  return matches;
});

另一种选择:使用reduce方法

如果你更习惯用reduce来累积结果,也可以这样写:

const sorted = work.reduce((resultArray, innerArray, outerIndex) => {
  const innerPosition = innerArray.indexOf(targetYear);
  if (innerPosition !== -1) {
    resultArray.push([outerIndex, innerPosition]);
  }
  return resultArray;
}, []);

这两种高阶方法都避免了手动写for循环,代码更简洁,也更符合现代JavaScript的写法。

内容的提问来源于stack exchange,提问作者Lammie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:13:09