Reputation: 1229
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;
Upvotes: 2
Views: 102
Reputation: 3411
Maybe this will helps.
var sumA = 0, sumB =0, sumC =0;
myArray.forEach(function(v){
if (v.hasOwnProperty("a") {sumA += v["a"];}
if (v.hasOwnProperty("b") {sumB += v["b"];}
if (v.hasOwnProperty("c") {sumC += v["c"];}
});
Upvotes: 1
Reputation: 122155
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);
Upvotes: 3
Reputation: 4612
forEach() could work :
var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var A = 0;
myArray.forEach(x => {A += x.a});
console.log(A); // 2
Upvotes: 0