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

如何对数组对象按type分组并计算amount总和生成指定数组

按type聚合金额总和的实现方案

方法一:使用reduce高效实现(推荐)

reduce可以一次性完成分组累加,仅遍历数组一次,性能更优:

const expenses = [
  {id:1, type:"books", title:"print book purchase", amount:50},
  {id:2, type:"books", title:"ebook purchase", amount:10},
  {id:3, type:"grocery", title:"vegetables", amount:5},
  {id:4, type:"grocery", title:"milk", amount:5},
  {id:5, type:"grocery", title:"eggs", amount:10}
];

// 按type累加金额,生成{ type: total }格式的对象
const sumMap = expenses.reduce((acc, item) => {
  // 若当前type未初始化,默认值设为0后累加
  acc[item.type] = (acc[item.type] || 0) + item.amount;
  return acc;
}, {});

// 将累加对象转换为目标数组格式
const result = Object.entries(sumMap).map(([type, total]) => ({ type, total }));

console.log(result);

输出结果:

[
  {type:'books',total:60},
  {type:'grocery',total:20}
]

方法二:基于你原有的双重循环思路修改

如果想沿用你原本的Set+双重循环逻辑,可以这样调整:

const expenses = [
  {id:1, type:"books", title:"print book purchase", amount:50},
  {id:2, type:"books", title:"ebook purchase", amount:10},
  {id:3, type:"grocery", title:"vegetables", amount:5},
  {id:4, type:"grocery", title:"milk", amount:5},
  {id:5, type:"grocery", title:"eggs", amount:10}
];

const typeSet = new Set(expenses.map(item => item.type));
const result = [];

// 外层循环遍历每个type
typeSet.forEach(currentType => {
  let total = 0;
  // 内层循环累加当前type的所有amount
  expenses.forEach(item => {
    if (item.type === currentType) {
      total += item.amount;
    }
  });
  // 将当前type的累加结果存入数组
  result.push({ type: currentType, total });
});

console.log(result);

两种方法都能得到你需要的输出,其中reduce的方式更适合数据量较大的场景,因为仅需遍历一次数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:15:48