jquery - Group and add values from JSON object -


i'm having trouble grouping , adding values json returned ajax query.

the data comes this:

0: object    count: 12   grp: 1   id: "1" 1: object    count: 21   grp: 2   id: "3" 2: object    count: 48   grp: 3   id: "4" 3: object    count: 51   grp: 2   id: "5" 

for grp there 5 possible options (groups): 1,2,3,4,5. want add count values each specific group. is, add grp 1 count values together, grp 2 count values together, , on.

what's best way this? can't figure out each or quite works.

var counts = {}; $.each(data, function(index, item){     var sum = counts[item.grp] || 0;     counts[item.grp] = sum + item.count; });  console.log(counts); # {1: 12, 2: 72, 3: 48} 

Comments