Adding up the values of an array of objects javascript

Viewed 85

I have an array of objects like this : const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]

i want an array like results = [{a:4 , b:5}] which is the sum of all values from the array of objects according to the key .

I tried something like this but sometimes it skipping the 1st object in the array :

       array.reduce((acc, n) => {
          for (var prop in n) {
            if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
            else acc[prop] = 0;
          }
          return acc;
        }, {})
4 Answers

You need to initialize acc before assigning, so small modification below will work

 const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]
 const res = array.reduce((acc, n) => {
          for (var prop in n) {
          acc[prop] = acc[prop] || 0; // Need to initialize before assigning
            if (n.hasOwnProperty(prop)) {
                 acc[prop] += n[prop];
               } 
          }
          return acc;
        }, {})
console.log(res);

This will work

const res = [{a:1, b:1, c: 1} , {a:2, b:3, c:3} ,{a:1, b:1, c: 3}].reduce((a,v,i) => {
    for(let key in v) {
      a[key] = a[key] ? a[key] + v[key] : v[key];
    }
    return a
},{})

console.log(res)

You can use this code and you won't have to specify the object properties manually, it will create a new property if it doesn't exist, or add to the existing property if it does exist.

var myarr = [{a: 2, b: 3}, {a:3, b:2}];
var newobj = {};

for (var i=0; i <= myarr.length; i += 1)   
  for (var p in myarr[i]) newobj[p] = (p in newobj) ? 
    newobj[p] + myarr[i][p] : myarr[i][p]
    
console.log(newobj);

use forEach and Object.entries will simplify.

const array = [
  { a: 1, b: 1 },
  { a: 2, b: 3 },
  { a: 1, b: 1 },
];

const acc = (arr) => {
  const res = {};
  arr.forEach((obj) =>
    Object.entries(obj).forEach(
      ([key, value]) => (res[key] = key in res ? res[key] + value : value)
    )
  );
  return [res];
};

console.log(acc(array));

Related