turtle
turtle

Reputation: 8083

Reduce over Javascript Object values

Is there a way to write a reduce function over Object values in Javascript? I'm looking for the analog of reducing over an array of keys:

Object.keys(hash).reduce(function(a, b) {

// reduce logic 

})

Upvotes: 0

Views: 177

Answers (2)

Bergi
Bergi

Reputation: 664599

No, there are no such native higher-order functions for objects.

You either will have to write your own, use a library (Underscore's _.reduce does work on objects as well) or apply the Array method on the keys like you just have:

 Object.keys(hash).reduce(function(sum, k) {
     return sum + hash[k];
 }, 0)

Upvotes: 1

Johan
Johan

Reputation: 35194

Is this what you need?

var o = { a:1, b:2, c:3 },
    values = [];

for(var k in o) {
    values.push(o[k]);
}

var result = values.reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
});

console.log(result);

http://jsfiddle.net/Mkm6e/

Upvotes: 0

Related Questions