JavaScript Sum of two objects with same properties

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 }
raja
Published on 21-Nov-2020 06:17:30
Advertisements