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

JavaScript 如何基于双条件对数组元素累计求和并保留所有元素

实现方案

之前的写法是把相同id和item的条目合并成单个聚合结果,所以会缺少原数组的元素。要保留所有原条目,只逐行累计total值,可使用如下原生JS实现:

const arr = [
  {id: 1, item: 'Mango', total: 5},
  {id: 1, item: 'Mango', total: 15},
  {id: 2, item: 'Apple', total: 8},
  {id: 2, item: 'Apple', total: 4}
];

// 缓存每个分组的累计和
const sumMap = {};
const result = arr.map(entry => {
  // 用id+item作为分组唯一标识
  const groupKey = `${entry.id}-${entry.item}`;
  sumMap[groupKey] = (sumMap[groupKey] || 0) + entry.total;
  // 返回新对象避免修改原数组
  return { ...entry, total: sumMap[groupKey] };
});

console.log(result);
/* 输出结果:
[
  {id: 1, item: 'Mango', total: 5},
  {id: 1, item: 'Mango', total: 20},
  {id: 2, item: 'Apple', total: 8},
  {id: 2, item: 'Apple', total: 12}
]
*/

如果允许直接修改原数组,可以简化为forEach写法:

const sumMap = {};
arr.forEach(entry => {
  const groupKey = `${entry.id}-${entry.item}`;
  sumMap[groupKey] = (sumMap[groupKey] || 0) + entry.total;
  entry.total = sumMap[groupKey];
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 19:54:09