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

JavaScript数组分组索引问题:将二维数组转换为指定键值结构

解决二维数组按子项索引分组的问题

核心思路

遍历原二维数组的每个子元素,将子元素中对应索引位置的值,收集到结果对象的对应键数组中,适配子项索引数量动态变化的场景。

方法一:for循环实现(直观易理解)

const input = [['S','Blue'],['M','Red'],['L','Yellow']];
const result = {};

// 先获取子数组的最大长度,确保覆盖所有可能的索引
const maxSubLength = input.length > 0 ? input[0].length : 0;

// 初始化每个索引对应的空数组
for (let i = 0; i < maxSubLength; i++) {
  result[i] = [];
}

// 遍历原数组的每个子数组,按索引归类元素
for (const subArr of input) {
  subArr.forEach((item, index) => {
    // 兼容子数组长度不一致的情况(如果有的子项更长)
    if (!result[index]) result[index] = [];
    result[index].push(item);
  });
}

console.log(result); // { 0: ['S','M','L'], 1: ['Blue','Red','Yellow'] }

方法二:reduce函数实现(简洁高效)

const input = [['S','Blue'],['M','Red'],['L','Yellow']];

const result = input.reduce((acc, subArr) => {
  subArr.forEach((item, index) => {
    // 自动初始化不存在的索引数组
    acc[index] = acc[index] || [];
    acc[index].push(item);
  });
  return acc;
}, {});

console.log(result);

边界情况处理

如果输入的二维数组存在子数组长度不一致的情况(比如[[1,2],[3],[4,5,6]]),上述两种方法都会自动处理,生成对应结构:

// 输入:[[1,2],[3],[4,5,6]]
// 输出:{ 0: [1,3,4], 1: [2,5], 2: [6] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:55:15