How to sum the values of a JavaScript object?

Jonathan Vanasco picture Jonathan Vanasco · May 8, 2013 · Viewed 142.8k times · Source

I'd like to sum the values of an object.

I'm used to python where it would just be:

sample = { 'a': 1 , 'b': 2 , 'c':3 };
summed =  sum(sample.itervalues())     

The following code works, but it's a lot of code:

function obj_values(object) {
  var results = [];
  for (var property in object)
    results.push(object[property]);
  return results;
}

function list_sum( list ){
  return list.reduce(function(previousValue, currentValue, index, array){
      return previousValue + currentValue;
  });
}

function object_values_sum( obj ){
  return list_sum(obj_values(obj));
}

var sample = { a: 1 , b: 2 , c:3 };
var summed =  list_sum(obj_values(a));
var summed =  object_values_sum(a)

Am i missing anything obvious, or is this just the way it is?

Answer

Michał Perłakowski picture Michał Perłakowski · Aug 19, 2016

It can be as simple as that:

const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);

Quoting MDN:

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

from Object.values() on MDN

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

from Array.prototype.reduce() on MDN

You can use this function like that:

sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5

Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.