Add matching object values in JavaScript


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

So, the resultant object should look like −

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

{ a: 6, b: 9, c: 6, d: 3 }

Updated on: 21-Oct-2020

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements