Search code examples
javascriptnode.jsunderscore.jslodash

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?


Solution

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

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