I have an array with 2 objects.
var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];
How can I sum the value in each object using just reduce/map/filter/forEach function?
The output should be [10, 14]
You could map the objects and the values by iterating the keys of ths object and add the value of all properties.
Methods used:
Array#map for returning a result for every item
Object.keys for getting all own properties of an object
Array#reduce for summing up the values
var data = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }],
sum = data.map(function (object) {
return Object.keys(object).reduce(function (sum, key) {
return sum + object[key];
}, 0);
});
console.log(sum);
Sum without key 'a'
var data = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }],
sum = data.map(function (object) {
return Object.keys(object).reduce(function (sum, key) {
return sum + (key !== 'a' && object[key]);
}, 0);
});
console.log(sum);
sum = data.map(o => Object.keys(o).reduce((s,k) => s + o[k], 0));Short solution using Array.prototype.reduce() function:
var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}],
result = sum.reduce(function (r, o) {
r.push(Object.keys(o).reduce(function(r, b){ return r + o[b]; }, 0));
return r;
}, []);
console.log(result);