user1876246 user1876246 - 4 months ago 8
Javascript Question

Iterate over an array of objects and add values together

This seems basic but I can't figure it out. I have the following array

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];


I want to loop through this array and add all the a's,b's,c's together. I want to do it in a loop because I don't know how many objects are inside the array.

Such as:

var A = myArray[0].a + myArray[1].a + myArray[2].a;

Answer

You can use reduce() and return result for each key in separate variables.

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var A = myArray.reduce(function(r, e) {
  return r + e.a;
}, 0)

console.log(A)

Or you can use reduce() and Object.keys() to return sum for each object's property in one variable.

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var result = myArray.reduce(function(r, e) {
  Object.keys(e).forEach(function(k) {
    r[k] = (r[k] || 0) + e[k];
  });
  return r;
})

console.log(result);

Comments