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

如何将二维数组同位置元素重组为以索引为键的对象?

解决二维数组转按列索引为键的对象问题

要实现把二维数组转换为键是列索引、值为对应列所有元素的数组的对象,这里提供几种简洁的JavaScript实现方式:

方法一:使用Array.prototype.reduce结合forEach

遍历原数组的每一行,再遍历行内每个元素,按列索引将元素归类到结果对象中:

const arr = [
  [0, 2, 5],
  [19, 4, 7],
  [98, 12, 3]
];

const result = arr.reduce((acc, row) => {
  row.forEach((val, colIndex) => {
    if (!acc[colIndex]) {
      acc[colIndex] = [];
    }
    acc[colIndex].push(val);
  });
  return acc;
}, {});

console.log(result);
// 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 7, 3] }

方法二:先确定最大列数,再逐列提取

如果数组中行的长度不一致,可先获取最长行的列数,再循环每一列收集元素(自动忽略行中不存在的列元素):

const arr = [
  [0, 2, 5],
  [19, 4],
  [98, 12, 3, 8]
];

// 获取最长行的列数
const maxCols = Math.max(...arr.map(row => row.length));
const result = {};

for (let col = 0; col < maxCols; col++) {
  result[col] = arr.map(row => row[col]).filter(val => val !== undefined);
}

console.log(result);
// 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 3], 3: [8] }

方法三:使用Object.fromEntries(ES2019+)

若环境支持ES2019及以上,可结合Object.fromEntries简化代码,同样基于最大列数处理:

const arr = [
  [0, 2, 5],
  [19, 4, 7],
  [98, 12, 3]
];

const maxCols = Math.max(...arr.map(row => row.length));
const result = Object.fromEntries(
  Array.from({ length: maxCols }, (_, col) => [
    col,
    arr.map(row => row[col]).filter(val => val !== undefined)
  ])
);

console.log(result);
// 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 7, 3] }

可根据数组结构和运行环境选择合适的实现方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:15:41