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

求助:如何用JS按值对嵌套数组进行分组?

如何按嵌套数组首元素分组重组数组内容?

问题描述

输入为两层嵌套数组,需要将所有子项按其首元素(名称)分组,把相同名称的项归到同一子数组中,最终得到目标结构:

输入数组:

[ 
  [ ["Mangas", 23809.132685271947], ["Magazines", 2162.858571621124], ["Journal", 0], ["Livres", 2533.654678438289] ],
  [ ["Mangas", 25809.508799386324], ["Magazines", 2519.527899187236], ["BDs", 0], ["Livres", 2436.7144208655627] ]
]

期望输出:

[ 
  [ ["Mangas", 23809.132685271947], ["Mangas", 25809.508799386324] ],
  [ ["Magazines", 2162.858571621124], ["Magazines", 2519.527899187236] ],
  [ ["Livres", 2533.654678438289], ["Livres", 2436.7144208655627] ],
  [ ["Journal", 0] ],
  [ ["BDs", 0] ]
]

解决方案

核心步骤是先扁平化嵌套数组,再按首元素分组,最后转换为目标结构:

// 输入数组
const input = [
  [ ["Mangas", 23809.132685271947], ["Magazines", 2162.858571621124], ["Journal", 0], ["Livres", 2533.654678438289] ],
  [ ["Mangas", 25809.508799386324], ["Magazines", 2519.527899187236], ["BDs", 0], ["Livres", 2436.7144208655627] ]
];

// 1. 扁平化数组,将两层嵌套转为单层
const flatItems = input.flat();

// 2. 用reduce按首元素分组
const groupedMap = flatItems.reduce((map, item) => {
  const name = item[0];
  if (!map.has(name)) {
    map.set(name, []);
  }
  map.get(name).push(item);
  return map;
}, new Map());

// 3. 将Map的取值转换为目标数组结构
const output = Array.from(groupedMap.values());

console.log(output);

说明

之前使用groupBy类方法失败,大概率是没先做扁平化处理——原输入是两层嵌套,直接分组会处理外层子数组而非单个数据项,扁平化后才能正确遍历到每个需要分组的元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:47:36