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

如何为二维数组中首元素为true的子数组添加原索引?

问题与解决方案

需求说明

给定如下二维数组:

const input = [
  [true, 'a', 'aa', 'aaa'],
  [false, 'b', 'bb', 'bbb'],
  [true, 'c', 'cc', 'ccc']
];

期望输出仅保留首元素为true的子数组,并在每个子数组开头添加其在原数组中的索引,结果如下:

const result = [
  [0, true, 'a', 'aa', 'aaa'],
  [2, true, 'c', 'cc', 'ccc']
];

遇到的问题

尝试先使用.map()结合unshift()添加索引,再用.filter()筛选符合条件的子数组,但unshift()返回的是数组长度,导致map()结果为[5,5,5],后续filter()执行后得到空数组。完整代码如下:

const input = [
  [true, 'a', 'aa', 'aaa'],
  [false, 'b', 'bb', 'bbb'],
  [true, 'c', 'cc', 'ccc']
];

const result = input.map((arr, i) => arr.unshift(i)).filter(arr => arr[1]);
console.log(result); // []

问题原因

  • unshift()返回值特性:Array.prototype.unshift()的返回值是修改后数组的长度,而非修改后的数组本身,所以map()最终返回的是长度数组[5,5,5],不是带索引的子数组。
  • 筛选逻辑失效:filter()遍历的是长度数组,每个元素都是数字,访问arr[1]会得到undefined,布尔转换后为false,因此最终得到空数组。
  • 额外副作用:unshift()会直接修改原数组结构,这通常是不需要的操作。

解决方案

方案一:先筛选再添加索引(推荐,无原数组修改)

先通过filter()保留符合条件的子数组并绑定索引,再用map()拼接索引与子数组:

const input = [
  [true, 'a', 'aa', 'aaa'],
  [false, 'b', 'bb', 'bbb'],
  [true, 'c', 'cc', 'ccc']
];

const result = input
  .map((arr, idx) => ({ idx, arr })) // 绑定索引与子数组
  .filter(item => item.arr[0]) // 筛选首元素为true的项
  .map(item => [item.idx, ...item.arr]); // 拼接索引与子数组

console.log(result);
// 输出:[[0, true, 'a', 'aa', 'aaa'], [2, true, 'c', 'cc', 'ccc']]

方案二:用reduce()一步完成

通过reduce()遍历数组,同时完成筛选与索引添加:

const input = [
  [true, 'a', 'aa', 'aaa'],
  [false, 'b', 'bb', 'bbb'],
  [true, 'c', 'cc', 'ccc']
];

const result = input.reduce((acc, arr, idx) => {
  if (arr[0]) {
    acc.push([idx, ...arr]); // 符合条件则拼接索引并推入结果数组
  }
  return acc;
}, []);

console.log(result);
// 输出:[[0, true, 'a', 'aa', 'aaa'], [2, true, 'c', 'cc', 'ccc']]

方案三:修复原逻辑(不推荐,会修改原数组)

若坚持先map后filter的顺序,需在map中返回修改后的数组,而非unshift()的返回值:

const input = [
  [true, 'a', 'aa', 'aaa'],
  [false, 'b', 'bb', 'bbb'],
  [true, 'c', 'cc', 'ccc']
];

const result = input
  .map((arr, i) => {
    arr.unshift(i); // 直接修改原数组
    return arr; // 返回修改后的数组
  })
  .filter(arr => arr[1]); // 此时arr[1]是原首元素,判断是否为true

console.log(result);
// 输出:[[0, true, 'a', 'aa', 'aaa'], [2, true, 'c', 'cc', 'ccc']]
// 注意:原input数组已被修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:30:53