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

TypeScript中合并同Zone属性数组元素的最简实现方法

解决方案:用Array.reduce实现分组合并

这其实是典型的分组合并对象场景,用Array.reduce就能用最少的代码搞定,而且效率很高——只需要遍历一次数组即可完成所有操作,完美符合你的需求。

完整TypeScript代码实现

// 先定义输入输出的类型,让代码更严谨
type InputItem = { Zone: string } & ({ Org: number } | { Mem: number });
type OutputItem = { Zone: string; Org: number; Mem: number };

// 你的原始输入数组
const input: InputItem[] = [
  {Zone: "4", Org: 1},
  {Zone: "2", Org: 1},
  {Zone: "4", Mem: 32},
  {Zone: "2", Mem: 22}
];

// 核心合并逻辑
const mergedResult: OutputItem[] = Object.values(
  input.reduce((accumulator, currentItem) => {
    const zoneKey = currentItem.Zone;
    // 合并已有属性和当前项的属性:如果accumulator里已有该Zone的对象,就扩展新属性;否则直接赋值当前项
    accumulator[zoneKey] = { ...accumulator[zoneKey], ...currentItem };
    return accumulator;
  }, {} as Record<string, OutputItem>) // 初始化累加器为一个空对象,类型为Zone字符串对应OutputItem的映射
);

console.log(mergedResult);
// 输出结果:[{Zone: "4", Org: 1, Mem: 32}, {Zone: "2", Org: 1, Mem: 22}]

代码逻辑解释

  1. reduce的作用:遍历输入数组,用一个对象(accumulator)作为累加器,以Zone的值为键,存储每个Zone对应的合并后对象。
  2. 属性合并:每次遍历到新项时,用扩展运算符...把当前项的属性合并到累加器对应Zone的对象中——如果该Zone之前已经存在,就会覆盖/补充属性;如果不存在,就直接创建新的对象。
  3. 转成数组:最后用Object.values()把累加器对象的所有值提取出来,转成你需要的数组格式。

对比你提到的方法

你之前想先创建Zone集合再遍历的方法是可行的,但需要额外遍历两次(一次收集Zone,一次合并),而用reduce只需要一次遍历,代码更简洁,效率也更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:54:11