Group By and Sum using Underscore/Lodash

I tried to do this in the functional way, and the result was like this

console.log(_.chain(data)
    .groupBy("platformId")
    .map(function(value, key) {
        return [key, _.reduce(value, function(result, currentObject) {
            return {
                payout: result.payout + currentObject.payout,
                numOfPeople: result.numOfPeople + currentObject.numOfPeople
            }
        }, {
            payout: 0,
            numOfPeople: 0
        })];
    })
    .object()
    .value());

In the spirit of lodash one liners

  _.map(_.groupBy(your_list, 'group_by'), (o,idx) => { return { id: idx, 
summed: _.sumBy(o,'sum_me') }})

You can do this without Underscore:

var result = data.reduce(function(acc, x) {
  var id = acc[x.platformId]
  if (id) {
    id.payout += x.payout
    id.numOfPeople += x.numOfPeople
  } else {
    acc[x.platformId] = x
    delete x.platformId
  }
  return acc
},{})

But why would you want an object with numeric keys? You could convert it back to a collection:

var toCollection = function(obj) {
  return Object.keys(obj)
    .sort(function(x, y){return +x - +y})
    .map(function(k){return obj[k]})
}

toCollection(result)

Note that objects are mutated, so you may to clone them first if you want to maintain the original data.


Here's a Lodash solution to this kind of problem. It's similar to Underscore, but with some more advanced features.

const data = [{
    platformId: 1,
    payout: 15,
    numOfPeople: 4
  },
  {
    platformId: 1,
    payout: 12,
    numOfPeople: 3

  },
  {
    platformId: 2,
    payout: 6,
    numOfPeople: 5

  },
  {
    platformId: 2,
    payout: 10,
    numOfPeople: 1
  },
];

const ans = _(data)
  .groupBy('platformId')
  .map((platform, id) => ({
    platformId: id,
    payout: _.sumBy(platform, 'payout'),
    numOfPeople: _.sumBy(platform, 'numOfPeople')
  }))
  .value()

console.log(ans);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>