过滤 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.