Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

javascript - Group By and Sum using Underscore/Lodash

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...