P粉4818158972023-08-15 15:34:26
This mission will be easier if divided into two parts.
First, reduce
it into an array containing the grouped values.
Then loop through (you can also use reduce) the object and get the sum of the array and add ${array.length} devices
to the string:
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)