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

如何使用TypeScript或JavaScript将数组转换为按首元素分组的新数组

数组分组转换解决方案

我来帮你搞定这个数组分组转换的问题,下面是具体的实现方案,不管是JavaScript还是TypeScript都有对应的解法哦~

需求回顾

你需要把一个二维数组按照子项的第一个元素分组,转换为包含panel和content字段的对象数组:

  • 原始数组:
const arrayList = [
  ['p1', 'm1', 0],
  ['p1', 'm2', 2],
  ['p1', 'm3', 3],
  ['p2', 'm2', 3],
  ['p2', 'm3', 5],
  ['p3', 'm1', 3],
  ['p3', 'm2', 4]
];
  • 目标结构:
const array2 = [
  { panel: 'p1', content: [['m1',0], ['m2', 2], ['m3', 3]] },
  { panel: 'p2', content: [['m2', 3], ['m3', 5]] },
  { panel: 'p3', content: [['m1', 3], ['m2', 4]] }
];

JavaScript 实现方案

可以用数组的reduce方法高效完成分组,逻辑清晰且代码简洁:

const arrayList = [['p1', 'm1', 0], ['p1', 'm2', 2], ['p1', 'm3', 3], ['p2', 'm2', 3], ['p2', 'm3', 5], ['p3', 'm1', 3], ['p3', 'm2', 4]];

const transformedArray = arrayList.reduce((acc, current) => {
  // 提取当前项的panel值和content子项
  const [panel, ...contentItem] = current;
  // 查找当前panel是否已存在于累加器中
  const existingGroup = acc.find(item => item.panel === panel);
  
  if (existingGroup) {
    // 如果存在,就把contentItem添加到对应的content数组里
    existingGroup.content.push(contentItem);
  } else {
    // 如果不存在,就新建一个分组对象加入累加器
    acc.push({ panel, content: [contentItem] });
  }
  
  return acc;
}, []);

console.log(transformedArray);

TypeScript 实现方案

如果用TypeScript,我们可以先定义好类型,让代码类型更安全:

// 定义原始数组子项的类型
type OriginalItem = [string, string, number];
// 定义转换后分组对象的类型
type GroupedItem = {
  panel: string;
  content: [string, number][];
};

const arrayList: OriginalItem[] = [['p1', 'm1', 0], ['p1', 'm2', 2], ['p1', 'm3', 3], ['p2', 'm2', 3], ['p2', 'm3', 5], ['p3', 'm1', 3], ['p3', 'm2', 4]];

const transformedArray: GroupedItem[] = arrayList.reduce((acc: GroupedItem[], current: OriginalItem) => {
  const [panel, ...contentItem] = current;
  const existingGroup = acc.find(item => item.panel === panel);
  
  if (existingGroup) {
    existingGroup.content.push(contentItem as [string, number]);
  } else {
    acc.push({ panel, content: [contentItem as [string, number]] });
  }
  
  return acc;
}, []);

console.log(transformedArray);

补充说明

  • reduce方法是处理这类分组问题的常用工具,它通过遍历数组逐步构建我们需要的结果
  • TypeScript版本里的类型断言as [string, number]是因为解构...contentItem得到的是数组,需要明确它的类型符合我们的定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 13:32:43