Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum properties from two objects?

Tags:

javascript

sum

I have multiple JavaScript objects:

{
  a: 12,
  b: 8,
  c: 17
}

and

{
  a: 2,
  b: 4,
  c: 1
}

I need to sum these two object by keys

Result:

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

Do you have any solutions in JavaScript? I use Object.keys.map but it's too long because I have like 100 elements in my object.

like image 408
Lionel B Avatar asked Feb 27 '17 14:02

Lionel B


2 Answers

You can use reduce for that, below function takes as many objects as you want and sums them by key:

var obj1 = {
  a: 12,
  b: 8,
  c: 17
};

var obj2 = {
  a: 12,
  b: 8,
  c: 17
};

var obj3 = {
  a: 12,
  b: 8,
  c: 17
};


function sumObjectsByKey(...objs) {
  return objs.reduce((a, b) => {
    for (let k in b) {
      if (b.hasOwnProperty(k))
        a[k] = (a[k] || 0) + b[k];
    }
    return a;
  }, {});
}

console.log(sumObjectsByKey(obj1, obj2, obj3));
like image 183
baao Avatar answered Sep 28 '22 07:09

baao


A little bit deeper, all you want as long as objects are equivalent!

const arr = [{
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  },
  {
    a: 12,
    b: { a: 12, c: { a: 12 } },
    c: 17
  }
];

const deepMergeSum = (obj1, obj2) => {
  return Object.keys(obj1).reduce((acc, key) => {
    if (typeof obj2[key] === 'object') {
      acc[key] = deepMergeSum(obj1[key], obj2[key]);
    } else if (obj2.hasOwnProperty(key) && !isNaN(parseFloat(obj2[key]))) {
      acc[key] = obj1[key] + obj2[key]
    }
    return acc;
  }, {});
};

const result = arr.reduce((acc, obj) => acc = deepMergeSum(acc, obj));
console.log('result: ', result);
like image 21
Carlos Rufo Avatar answered Sep 28 '22 07:09

Carlos Rufo