Sum the array of properties with a unique object_id

Let's say I have the following array of objects:

objects = [{id: 1, installs: 21}, {id: 2, installs: 10}, {id:1, installs: 11}, {id:3, installs:5}]

I want to summarize all the values installfor the same id. What is the best way to do this?

+4
source share
2 answers
objects = [{id: 1, installs: 21}, {id: 2, installs: 10}, {id: 1, installs: 11}, {id: 3, installs: 5}]

sums = Hash.new(0)  # sums returns 0 for an unknown key
objects.each{|h| sums[h[:id]] += h[:installs]}
p sums  # => {1=>32, 2=>10, 3=>5}
+4
source
sorted = objects.group_by{|x|x[:id]}
sorted.map{|x|x[1].inject(0){|sum, x| sum + x[:installs]}}
0
source

All Articles