Skip to content
Advertisement

Javascript reduce() on Object

There is nice Array method reduce() 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 reduce() method implemented.

Advertisement

Answer

What you actually want in this case are the Object.values. Here is a concise ES6 implementation with that in mind:

const add = {
  a: {value:1},
  b: {value:2},
  c: {value:3}
}

const total = Object.values(add).reduce((t, {value}) => t + value, 0)

console.log(total) // 6

or simply:

const add = {
  a: 1,
  b: 2,
  c: 3
}

const total = Object.values(add).reduce((t, n) => t + n)

console.log(total) // 6
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement