Add values of matching keys in array of objects - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects like this −

const arr = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];

Each object is bound to have unique keys in itself (for it to be a valid object), but two different objects can have the common keys (for the purpose of this question)

We are required to write a JavaScript function that takes in one such array and returns an object with all the unique keys present in the array and their values cumulative sum as the value

Therefore, the resultant object should look like −

const output = {a: 6, b: 9, c: 6, d: 3};

Example

Following is the code −

const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d:1}, {a: 1, d: 2}];
const sumArray = arr => {
   const res = {};
   for(let i = 0; i < arr.length; i++){
      Object.keys(arr[i]).forEach(key => {
         res[key] = (res[key] || 0) + arr[i][key];
      });
   };
   return res;
};
console.log(sumArray(arr));

Output

This will produce the following output in console −

{ a: 6, b: 9, c: 6, d: 3 }
raja
Published on 18-Sep-2020 16:52:25
Advertisements