搜索

首页  >  问答  >  正文

计算每个reduce操作的互动次数

<p>我有一个对象列表,如下:</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>我正在按货币进行求和,如下:</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>它返回一个对象,如下:</p> <pre class="brush:php;toolbar:false;">{ EUR: 522.3 GBP: 2,098.17 }</pre> <p>我还想返回每种货币的设备总数,类似于:</p> <pre class="brush:php;toolbar:false;">{ EUR: 522.3 (1个设备) GBP: 2,098.17 (2个设备) }</pre> <p>尝试添加另一个循环,但结果不如预期。</p>
P粉191323236P粉191323236469 天前494

全部回复(1)我来回复

  • P粉481815897

    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)

    回复
    0
  • 取消回复