0

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 

})
0

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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/

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.