4

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?

5 Answers 5

4

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

2 Comments

Thank you for the answer Travis. Is there a way you can see of doing this with underscore or lodash?
@Leon: Underscore has _.reduce if you don't want to use standard JavaScript.
2

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

_.spread(_.merge)([{}].concat(array, _.add));
// → { a: 8, b: 5, d: 6, c: 13 }

2 Comments

No clue how it works but this is a brilliant solution using lodash.
Any way someone can explain how this works. I don't get how concat can help having the values added.
2

You can try this solution:

var arr = [{"a":4,"b":5, "d":6}, {"a":4, "c":5}, {"c":4}];
var result = {};
arr.forEach(function(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
        result[prop] = (result[prop] || 0) + obj[prop];
    }
  }
});

$('#result').text(JSON.stringify(result,null,2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="result"></div>

Comments

2

_.merge with a custom callback would do:

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

var result = _.merge.apply(null, array.concat([function(a, b) {
  if (typeof a === 'number') {
    return a + b;
  }
}]));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>

2 Comments

This mutates the first element of array, FYI.
@AdamBoduch: true. Should be solvable by injecting an empty object at the beginning.
0

As of lodash 4.0.0 this is simple using mergeWith:

_.mergeWith({}, ...array, _.add)

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.