JavaScript Sum of two objects with same properties


Suppose, we have two objects like these −

const obj1 = {
   a:12, b:8, c:17
};
const obj2 = {
   a:2, b:4, c:1
};

We are required to write a JavaScript function that takes in two such object.

The function should sum the values of identical properties into a single property. Therefore, the final object should look something like this −

const output = {
   a:14, b:12, c:18
};

Note − For the sake of simplicity, we have just used two objects, but we are required to write our function such that it can take in any number of objects and add their property values.

Example

const obj1 = {
   a:12,
   b:8,
   c:17
};
const obj2 = {
   a:2,
   b:4,
   c:1
};
const sumObjectsByKey = (...objs) => {
   const res = objs.reduce((a, b) => {
      for (let k in b) {
         if (b.hasOwnProperty(k))
         a[k] = (a[k] || 0) + b[k];
      }
      return a;
   }, {});
   return res;
}
console.log(sumObjectsByKey(obj1, obj2));

Output

And the output in the console will be −

{ a: 14, b: 12, c: 18 }

Updated on: 21-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements