How to sum the values of a JavaScript object?

后端 未结 14 694
梦如初夏
梦如初夏 2020-11-27 04:03

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(sampl         


        
相关标签:
14条回答
  • 2020-11-27 04:21

    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 );
    console.log( "sum: "+summed );


    For fun's sake here is another implementation using Object.keys() and Array.reduce() (browser support should not be a big issue anymore):

    function sum(obj) {
      return Object.keys(obj).reduce((sum,key)=>sum+parseFloat(obj[key]||0),0);
    }
    let sample = { a: 1 , b: 2 , c:3 };
    
    console.log(`sum:${sum(sample)}`);

    But this seems to be way slower: jsperf.com

    0 讨论(0)
  • 2020-11-27 04:23

    A regular for loop is pretty concise:

    var total = 0;
    
    for (var property in object) {
        total += object[property];
    }
    

    You might have to add in object.hasOwnProperty if you modified the prototype.

    0 讨论(0)
  • 2020-11-27 04:24

    Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:

    const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
    

    Our accumulator acc, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!

    0 讨论(0)
  • 2020-11-27 04:25

    If you're using lodash you can do something like

    _.sum(_.values({ 'a': 1 , 'b': 2 , 'c':3 })) 
    
    0 讨论(0)
  • 2020-11-27 04:26

    A ramda one liner:

    import {
     compose, 
     sum,
     values,
    } from 'ramda'
    
    export const sumValues = compose(sum, values);
    

    Use: const summed = sumValues({ 'a': 1 , 'b': 2 , 'c':3 });

    0 讨论(0)
  • 2020-11-27 04:27

    Use Lodash

     import _ from 'Lodash';
     
     var object_array = [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}];
     
     return _.sumBy(object_array, 'c')
     
     // return => 9

    0 讨论(0)
提交回复
热议问题