Pavel S. Pavel S. - 1 year ago 81
Javascript Question

Javascript reduce() on Object

There is nice Array method

to get one value from the Array. Example:

[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;

What is the best way to achieve the same with objects? I'd like to do this:

a: {value:1},
b: {value:2},
c: {value:3}
}.reduce(function(previous, current, index, array){
return previous.value + current.value;

However, Object does not seem to have any
method implemented.


One option would be to reduce the keys():

var o = { 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 

Object.keys(o).reduce(function (previous, key) {
    return previous + o[key].value;
}, 0);

With this, you'll want to specify an initial value or the 1st round will be 'a' + 2.

If you want the result as an Object ({ value: ... }), you'll have to initialize and return the object each time:

Object.keys(o).reduce(function (previous, key) {
    previous.value += o[key].value;
    return previous;
}, { value: 0 });