Sum JavaScript arrays repeated value

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

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

We are required to write a JavaScript function that takes in one such array and sums the value of all identical keys together.

Therefore, the summed array should look like −

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

Example

The code for this will be −

const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}];
const sumDuplicate = arr => {
   const map = {};
   for(let i = 0; i < arr.length; ){
      const key = Object.keys(arr[i])[0];
      if(!map.hasOwnProperty(key)){
         map[key] = i++;
         continue;
      };
      arr[map[key]][key] += arr[i][key];
      arr.splice(i, 1);
   };
};
sumDuplicate(arr);
console.log(arr);

Output

And the output in the console will be −

[ { 'TR-01': 4 }, { 'TR-02': 8 } ]
raja
Published on 20-Nov-2020 10:06:15
Advertisements