I have this array of pairs:
[{"a"=>"1"}, {"b"=>"2"}, {"a"=>"3"}, {"b"=>"4"}, {"a"=>"5"}]
I would like a method to merge the keys in common with multiple values to:
[{"a"=>["1","3","5"]}, {"b"=>["2","4"]}]
Improved following Marc-Andre's suggestion.
array = [{"a"=>"1"}, {"b"=>"2"}, {"a"=>"3"}, {"b"=>"4"}, {"a"=>"5"}]
array.group_by(&:keys).map{|k, v| {k.first => v.flat_map(&:values)}}
Or
array.group_by{|h| h.keys.first}.each_value{|a| a.map!{|h| h.values.first}}
Haven't tried it yet, but something like that should also works
a.each_with_object( Hash.new{ |h,k| h[k] = [] } ) do |x, hash|
hash[x.keys.first] << x.values.first
end
edit: For a one liner, and the same output :
[a.each_with_object( Hash.new{ |h,k| h[k] = [] } ) { |x, hash| hash[x.keys.first] << x.values.first }]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With