2

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]

0

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or, equivalently, using shorthand: sum = data.map(o => Object.keys(o).reduce((s,k) => s + o[k], 0));
Thanks, how about if I want to sum (b c d) only, except the (a). The output will be [9, 12].
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);

1 Comment

what if you have object like this category:{'1':200,'2':300}
0

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

Comments

0

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]

Comments

0

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.