简体   繁体   中英

How to sum up all items in an object array?

I have an array of objects:

var test = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6},{"a":7, "b":8, "c":9}];

I would like to add up all the values in object b to get the total 15

Use reduce instead like this:

 var test = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6},{"a":7, "b":8, "c":9}]; var sum = test.reduce((s, o) => s + ob, 0); console.log(sum);

Note : This test.reduce((s, o) => s + ob, 0) uses an arrow function . It's the same as:

test.reduce(function(s, o) {
    return s + o.b;
}, 0);

The method to get a single value back from an array of values is Array#reduce , you give it an accumulator function and an optional starting value and it applies it to each element until it gets the final value:

var test = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6},{"a":7, "b":8, "c":9}];

test
  .map(function pluckB(o) { return o.b }) // Take only the 'b' property
  // => [2,5,8]
  .reduce(function add(a, b) { return a + b }, 0); // Sum them, starting from 0
  // => 15

It can get even terser with ES2015 arrow functions :

test.map(o => o.b).reduce((a, b) => a + b, 0)

And with a functional utility library such as Ramda , it's just a call to two functions:

R.sum(R.pluck('b', test))

As @ibrahim mahrir may have wanted to hint at in the comments, in JavaScript it can be more performant to actually compose such operations together and only iterate through the array once instead of using a pipeline style. That's because .map , .filter and co. create new array copies instead of modifying the array in place, and that instantiation has a cost.
But unless this code is running in a very tight loop, the performance impact will be absolutely negligible compared to the increased maintainability of using the most readable solution.

If you want to find the sum of each object in the array, iterate the array overwriting the current element with the sum of the values.

 var test = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6},{"a":7, "b":8, "c":9}]; test.forEach((e, i, a) => a[i] = Object.values(e).reduce((x, y) => x + y, 0)); console.log(test)

If you want to find the sum of the values of the matching properties of each object in the array, iterate the array creating a new object and add the values based on the key.

 var test = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6},{"a":7, "b":8, "c":9}]; var result = test.reduce((o, e) => { for(var i in e) o[i] = (o[i] || 0) + e[i]; return o; }, {}); console.log(result);

You'll notice that the values of the second object equal 15, as well as all of the values of the properties named "b", so it is not entirely clear what you're after here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM