Group By and Sum using Underscore/Lodash

2019-01-23 06:31发布

I have JSON like this:

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

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

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

]

And I want to Group it by platformId with sum of payout and numOfPeople.

I.e. in result I want JSON like this:

[
  "1": {
     payout: 27,
     numOfPeople: 7
   },

  "2": {
     payout: 16,
     numOfPeople: 6
  }
] 

I tried to use underscore.js's _.groupBy method, and it groups fine, but how I can get the SUM of objects properties values like I demonstrated above?

5条回答
【Aperson】
2楼-- · 2019-01-23 07:05

A (in my opinion) nice functional way using underscore.js:

var sum = function(t, n) { return t + n; };
_.mapObject(
    _.groupBy(data, 'platformId'),
    function(values, platformId) {
        return {
            payout: _.reduce(_.pluck(values, 'payout'), sum, 0),
            numOfPeople: _.reduce(_.pluck(values, 'numOfPeople'), sum, 0)
        };
    }
);
查看更多
欢心
3楼-- · 2019-01-23 07:10

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());
查看更多
4楼-- · 2019-01-23 07:12

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.

查看更多
干净又极端
5楼-- · 2019-01-23 07:21

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>

查看更多
戒情不戒烟
6楼-- · 2019-01-23 07:23
//Input 
[{
  "platformId": 1,
  "payout": 15,
  "numOfPeople": 4
}, {
  "platformId": 1,
  "payout": 12,
  "numOfPeople": 3
}, {
  "platformId": 2,
  "payout": 6,
  "numOfPeople": 5
}, {
  "platformId": 2,
  "payout": 10,
  "numOfPeople": 1
}]


//Output
{
 "1": {
    "payout": 43,
    "numOfPeople": 13
 },
 "2": {
    "payout": 43,
    "numOfPeople": 13
 }
}


// Code
output = _.reduce(input, function(acc, val, key) {
  acc[val.platformId] = {
     payout: _.sum(a, 'payout'),
     numOfPeople: _.sum(a, 'numOfPeople')
   };
  return acc;
  }, {});
查看更多
登录 后发表回答