search

Home  >  Q&A  >  body text

Count the number of interactions for each reduce operation

<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粉191323236P粉191323236456 days ago480

reply all(1)I'll reply

  • P粉481815897

    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)

    reply
    0
  • Cancelreply