P粉4818158972023-08-15 15:34:26
這個任務分成兩個部分會比較容易。
首先,將其reduce
為一個包含分組值的陣列。
然後循環遍歷(也可以使用reduce)對象,並獲取數組的總和,並將${array.length} devices
添加到字串中:
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 } } let grouped = Object.values(usageCosts).reduce((p, c) => { if (!p[c.currency]) p[c.currency] = []; p[c.currency].push(c.yearlyUsage); return p; }, {}); for (var key in grouped) { grouped[key] = `${grouped[key].reduce((a,b)=>a+b)} (${grouped[key].length}) devices`; } console.log(grouped)