Jonathan Vanasco Jonathan Vanasco - 5 months ago 17
Javascript Question

a concise way to sum the values of a javascript object?

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

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

You could put it all in one function:

function sum( obj ) {
  var sum = 0;
  for( var el in obj ) {
    if( obj.hasOwnProperty( el ) ) {
      sum += parseFloat( obj[el] );
    }
  }
  return sum;
}

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


For fun's sake here is another implementation using Object.keys() and Array.reduce() (browser support might be an issue, though):

function sum( obj ) {
  return Object.keys( obj )
               .reduce( function( sum, key ){
                 return sum + parseFloat( obj[key] );
               }, 0 );
}

But this seems to be way slower: jsperf.com