如何用JavaScript的reduce同时统计货币年用量及对应设备数量?
按货币汇总年使用量并统计设备数量
你可以通过调整reduce的累加器结构,先记录每个货币的总使用量和设备数量,最后再格式化为目标字符串。具体实现如下:
原始数据
const usageCosts = { 224910186407: { deviceId: "224910186407", currency: "GBP", yearlyUsage: 1480.81 }, 224910464538: { deviceId: "224910464538", currency: "GBP", yearlyUsage: 617.36 }, 224910464577: { deviceId: "224910464577", currency: "EUR", yearlyUsage: 522.3 } }
修改后的实现代码
// 第一步:用reduce统计总使用量和设备数量 const intermediateResult = Object.values(usageCosts).reduce( (acc: { [key: string]: { total: number; count: number } }, stat) => { const currency = stat.currency; if (!currency) return acc; // 初始化当前货币的统计项 if (!acc[currency]) { acc[currency] = { total: 0, count: 0 }; } // 更新总使用量和设备数 acc[currency].total += stat.yearlyUsage; acc[currency].count += 1; return acc; }, {} ); // 第二步:格式化为目标字符串格式 const totalYearlyCost = Object.fromEntries( Object.entries(intermediateResult).map(([currency, { total, count }]) => { // 格式化数字(保留两位小数,添加千分位分隔符) const formattedTotal = total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); // 生成设备数文本 const deviceText = count === 1 ? `${count} device` : `${count} devices`; return [currency, `${formattedTotal} (${deviceText})`]; }) ); console.log(totalYearlyCost);
输出结果
{ EUR: "522.30 (1 device)", GBP: "2,098.17 (2 devices)" }
代码说明
- 中间统计阶段:累加器
acc的每个键对应一个对象,存储该货币的total(总使用量)和count(设备数量),遍历每个设备时直接更新这两个值,比原代码的解构赋值更高效。 - 格式转换阶段:通过
Object.fromEntries和map将中间统计结果转换成目标格式,同时处理数字的千分位格式化、小数位数保留,以及设备数的单复数文本逻辑。
内容的提问来源于stack exchange,提问作者Marks
相关产品推荐
相关产品推荐

