Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Sum array of object values

I would think this is a surprisingly common and simple question but I cant seem to find what Im looking for

If I had

var array = [{"a":4,"b":5, "d":6}, {"a":4, "c":5}, {"c":4}]

how do I sum the objects to get

{"a":8,"b":5,"c":9, "d":6}

using underscore, lodash, or something fairly quick and simple one liner?

like image 834
Leon Avatar asked Dec 24 '22 15:12

Leon


2 Answers

You should be able to use reduce for this

var compact = array.reduce(function(prev,cur){
 for(var key in cur){
  if(!cur.hasOwnProperty(key))continue;
  if(prev.hasOwnProperty(key)){
   prev[key] += cur[key];
  }else{
   prev[key] = cur[key];
  }
 }
 return prev;
},{});
like image 144
Travis J Avatar answered Dec 27 '22 05:12

Travis J


You could combine spread(), merge(), and add() to produce:

_.spread(_.merge)([{}].concat(array, _.add));
// → { a: 8, b: 5, d: 6, c: 13 }
like image 36
Adam Boduch Avatar answered Dec 27 '22 03:12

Adam Boduch