You need to enable JavaScript to run this app. JavaScript如何重组多维数组为指定格式 优先使用ES6语法实现
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何重组多维数组为指定格式 优先使用ES6语法实现

JS多维数组合并实现方案

可以实现,该需求的核心逻辑是将原数组中每两个连续的子数组合并:下标为偶数的子数组为列标题组,下一个奇数下标的子数组为该列的内容组,合并后即可得到你需要的目标结构。

核心实现代码(ES6语法)

// 输入的原始多维数组
const originArr = [['a'], ['a1', 'a2'], ['b'], ['b1', 'b2', 'b4', 'b9']];

// 数组合并处理
const targetArr = originArr.reduce((result, current, index) => {
  // 仅处理偶数索引的标题项,和后一位的内容项合并
  if (index % 2 === 0) {
    result.push([...current, ...originArr[index + 1]]);
  }
  return result;
}, []);

console.log(targetArr) 
// 输出:[['a', 'a1', 'a2'], ['b', 'b1', 'b2', 'b4', 'b9']]

拓展:直接生成表格渲染结构

如果需要直接生成适配表格渲染的行格式数据(空位自动补空字符串),可以补充以下逻辑:

// 计算内容部分最长的行数
const maxRowCount = Math.max(...targetArr.map(col => col.length - 1));

// 生成表格渲染用二维数组,结构为[表头行, 内容行1, 内容行2...]
const tableData = [
  // 表头行
  targetArr.map(col => col[0]),
  // 逐行生成内容
  ...Array.from({length: maxRowCount}, (_, rowIndex) => 
    targetArr.map(col => col[rowIndex + 1] ?? '')
  )
];

/*
tableData输出结果:
[
  ['a', 'b'],
  ['a1', 'b1'],
  ['a2', 'b2'],
  ['', 'b4'],
  ['', 'b9']
]
*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 19:09:04