How to merge array of hash based on the same keys in ruby?

Try

a.flat_map(&:entries)
  .group_by(&:first)
  .map{|k,v| Hash[k, v.map(&:last)]}

Another alternative:

a = [{:a=>1},{:a=>10},{:b=>8},{:c=>7},{:c=>2}]

p a.each_with_object({}) { |h, o| h.each { |k,v| (o[k] ||= []) << v } }
# => {:a=>[1, 10], :b=>[8], :c=>[7, 2]}

It also works when the Hashes have multiple key/value combinations, e.g:

b = [{:a=>1, :b=>5, :x=>10},{:a=>10, :y=>2},{:b=>8},{:c=>7},{:c=>2}]
p b.each_with_object({}) { |h, o| h.each { |k,v| (o[k] ||= []) << v } }
# => {:a=>[1, 10], :b=>[5, 8], :x=>[10], :y=>[2], :c=>[7, 2]}

Minor addition to answer by Arie Shaw to match required answer:

a.flat_map(&:entries)
  .group_by(&:first)
  .map{|k,v| Hash[k, v.size.eql?(1) ? v.last.last : v.map(&:last) ]}
#=> [{:a=>[1, 10]}, {:b=>8}, {:c=>[7, 2]}]

Tags:

Arrays

Ruby

Hash