過濾 JavaScript 中唯一的陣列值並求和


假設我們有一個類似的陣列 −

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];

我們應該編寫一個接受此類陣列的函式。請注意,所有子陣列中都恰好有三個元素。

我們的函式應該過濾掉具有重複值作為其第一個元素的子陣列。此外,對於移除的子陣列,我們應該將它們的第三個元素新增到現有的非重複對應的子陣列中。

因此,對於以上陣列,輸出應如下所示 −

const output = [[12345, "product", "25"],[1234567, "other", "10"]];

示例

程式碼如下 −

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567,
"other", "10"]];
const addSimilar = (arr = []) => {
   const res = [];
   const map = {};
   arr.forEach(el => {
      const [id, name, amount] = el;
      if(map.hasOwnProperty(id)){
         const newAmount = +amount + +res[map[id] - 1][2];
         res[map[id] - 1][2] = '' + newAmount;
      }else{
         map[id] = res.push(el);
      }
   });
   return res;
}
console.log(addSimilar(arr));

輸出

控制檯中的輸出如下 −

[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]

更新於: 2020-11-21

612 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.