Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  69] [ 6]  / answers: 1 / hits: 39759  / 10 Years ago, wed, july 30, 2014, 12:00:00

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?


More From » arrays

 Answers
19

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.


[#69988] Monday, July 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;