如何按shop与status分组合并数组并实现求和与统计?
JavaScript按Shop和Status分组求和并统计数量的实现方案
核心思路
利用Array.reduce()遍历数组,以shop + status的组合作为唯一分组键,在累加器中维护每个分组的数值总和与计数,最后将累加器对象转换为数组得到最终结果。
示例实现
假设输入数据
const inputData = [ { shop: "Shop A", status: "Paid", rent_total: 100, latefee_total: 10, amount_total: 110 }, { shop: "Shop A", status: "Paid", rent_total: 200, latefee_total: 20, amount_total: 220 }, { shop: "Shop A", status: "Unpaid", rent_total: 150, latefee_total: 15, amount_total: 165 }, { shop: "Shop B", status: "Paid", rent_total: 300, latefee_total: 0, amount_total: 300 }, ];
实现代码
// 分组处理逻辑 const groupedData = Object.values(inputData.reduce((acc, current) => { // 生成唯一分组标识:拼接shop和status const groupKey = `${current.shop}-${current.status}`; // 若分组不存在,初始化结构 if (!acc[groupKey]) { acc[groupKey] = { shop: current.shop, status: current.status, rent_total: 0, latefee_total: 0, amount_total: 0, total_shops: 0 }; } // 累加数值字段 acc[groupKey].rent_total += current.rent_total; acc[groupKey].latefee_total += current.latefee_total; acc[groupKey].amount_total += current.amount_total; // 统计该分组下的条目数量(即total_shops) acc[groupKey].total_shops += 1; return acc; }, {})); console.log(groupedData);
输出结果
[ { shop: "Shop A", status: "Paid", rent_total: 300, latefee_total: 30, amount_total: 330, total_shops: 2 }, { shop: "Shop A", status: "Unpaid", rent_total: 150, latefee_total: 15, amount_total: 165, total_shops: 1 }, { shop: "Shop B", status: "Paid", rent_total: 300, latefee_total: 0, amount_total: 300, total_shops: 1 } ]
自定义调整说明
如果total_shops需要统计分组内的唯一店铺数(而非条目数,例如存在同名不同店铺的场景),可以改用Set来维护:
const groupedData = Object.values(inputData.reduce((acc, current) => { const groupKey = `${current.shop}-${current.status}`; if (!acc[groupKey]) { acc[groupKey] = { shop: current.shop, status: current.status, rent_total: 0, latefee_total: 0, amount_total: 0, _uniqueShops: new Set() }; } acc[groupKey].rent_total += current.rent_total; acc[groupKey].latefee_total += current.latefee_total; acc[groupKey].amount_total += current.amount_total; acc[groupKey]._uniqueShops.add(current.shop); // 存储唯一店铺标识 return acc; }, {})).map(group => ({ ...group, total_shops: group._uniqueShops.size, _uniqueShops: undefined // 移除临时字段 }));
内容的提问来源于stack exchange,提问作者Abdul Razique
相关产品推荐
相关产品推荐

