Chikorio
Chikorio

Reputation: 65

JavaScript sum all of the values in each object in an array?

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]

Upvotes: 2

Views: 8451

Answers (6)

Redu
Redu

Reputation: 26201

You may do as follows in pure JS in 2017.

var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}],
   sums = sum.map(a => Object.values(a).reduce((p,c) => p+c));
console.log(sums);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386868

You could map the objects and the values by iterating the keys of ths object and add the value of all properties.

Methods used:

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);

Upvotes: 6

emilz0r
emilz0r

Reputation: 61

es6 for of version:

let sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];

let result = [], objSum;
for (let item of sum) {
    objSum = 0;
    for (let property in item) {
        if (item.hasOwnProperty(property)) {
            objSum += item[property];
        }
    }

    result.push(objSum);
}
console.log(result);//[10, 14]

Upvotes: 0

Andrew Willems
Andrew Willems

Reputation: 12458

In the following code, o is each object in the array, t is the accumulating total sum, p is the property of the object being added.

const sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];

const result = sum.map(o => Object.keys(o).reduce((t, p) => t + o[p], 0));

console.log(result);

Upvotes: 0

Nico Van Belle
Nico Van Belle

Reputation: 5166

Or you can use a utility library like Lodash.

var _ = require('lodash');

var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];
var result = _.map(sum, function(obj) {
      return _.reduce(_.values(obj), function(sum, n) {
          return sum + n;
      }, 0);
});
console.log(result);

Upvotes: -1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

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);

Upvotes: 0

Related Questions