总和数组重复值-JavaScript

假设我们有一个像这样的对象数组-

const arr = [
   {'ID-01':1},
   {'ID-02':3},
   {'ID-01':3},
   {'ID-02':5}
];

我们需要将所有具有相同键的对象的值加在一起

因此,对于此数组,输出应为-

const output = [{'ID-01':4}, {'ID-02':8}];

我们将遍历数组,检查具有相同键的现有对象,如果存在,则为其添加值,否则将新对象推入数组。

示例

以下是代码-

const arr = [
   {'ID-01':1},
   {'ID-02':3},
   {'ID-01':3},
   {'ID-02':5}
];
const indexOf = function(key){
   return this.findIndex(el => typeof el[key] === 'number')
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const key = Object.keys(arr[i])[0];
      const ind = res.indexOf(key);
      if(ind !== -1){
         res[ind][key] += arr[i][key];
      }else{
         res.push(arr[i]);
      };
   };
   return res;
};
console.log(groupArray(arr));

输出结果

这将在控制台中产生以下输出-

[ { 'ID-01': 4 }, { 'ID-02': 8 } ]