Sum arrays repeated value - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

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

We are required to add the values for all these objects together that have identical keys

Therefore, for this array, the output should be −

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

We will loop over the array, check for existing objects with the same keys, if they are there, we add value to it otherwise we push new objects to the array.

Example

Following is the code −

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));

Output

This will produce the following output in console −

[ { 'ID-01': 4 }, { 'ID-02': 8 } ]
raja
Published on 18-Sep-2020 13:18:44
Advertisements