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
相关产品推荐
相关产品推荐

