[2012, 10]}, {"key"=>[2012,...">

Group an array of hashes by a given key and accumulate values

Source (already ordered correctly):

rows = [{"key"=>[2012, 10]}, {"key"=>[2012, 9]}, {"key"=>[2011, 7]}]

Desired Result:

[[2012, [10, 9]], [2011, [7]]]
-1
source share
2 answers
rows.map {|row| row.values.flatten}.inject({}) {|h,r| h[r[0]].nil? ? h[r[0]] = [r[1]] : h[r[0]] << r[1];h }.to_a
# [[2012, [10, 9]], [2011, [7]]]

or

rows.map {|row| row.values.flatten}.inject({}) {|h,r| h[r[0]] ||= []; h[r[0]] << r[1];h }.to_a
# [[2012, [10, 9]], [2011, [7]]]
+1
source

Since the data is pre-ordered, we can use chunkinstead group_by:

rows.chunk { |h| h.values.first[0] }.map do |year, hs| 
  [year, hs.map { |h| h.values.first[1] }]
end
#=> [[2012, [10, 9]], [2011, [7]]]
+2
source

Source: https://habr.com/ru/post/1661599/


All Articles