Count the number of interactions for each reduce operation
P粉191323236
P粉191323236 2023-08-14 17:21:30
0
1
484
<p>I have a list of objects as follows: </p> <pre class="brush:php;toolbar:false;">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 } }</pre> <p>I'm doing a sum by currency, like this: </p> <pre class="brush:php;toolbar:false;">const totalYearlyCost = Object.values(usageCosts).reduce( (acc: { [key: string]: any }, stat: any) => { if (stat.currency && !acc[stat.currency]) { acc[stat.currency] = 0 } return { ...acc, [stat.currency!]: acc[stat.currency!] stat.yearlyUsage, } }, {}, )</pre> <p>It returns an object as follows: </p> <pre class="brush:php;toolbar:false;">{ EUR: 522.3 GBP: 2,098.17 }</pre> <p>I also want to return the total number of devices per currency, something like: </p> <pre class="brush:php;toolbar:false;">{ EUR: 522.3 (1 device) GBP: 2,098.17 (2 devices) }</pre> <p>Tried adding another loop, but the results were not as expected. </p>
P粉191323236
P粉191323236

reply all(1)
P粉481815897

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template