搜尋

首頁  >  問答  >  主體

計算每個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粉191323236472 天前500

全部回覆(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
  • 取消回覆