Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

hash

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

example :

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

How to get result like this?

a = [{:a=>[1, 10]},{:b=>8},{:c=>[7, 2]}]
like image 631
tardjo Avatar asked Mar 11 '14 06:03

tardjo


People also ask

How do you combine hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How do you combine Hash?

Hash#merge!() is a Hash class method which can add the content the given hash array to the other. Entries with duplicate keys are overwritten with the values from each other_hash successively if no block is given.

How do you push values into an array of Hash in Ruby?

You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

What is associative array in Ruby?

Ruby | Array assoc() function The assoc() function in Ruby is used to search through an array of arrays whose first element is compared with the index of the function and return the contained array if match found otherwise return either nil or vacant.


2 Answers

Try

a.flat_map(&:entries)
  .group_by(&:first)
  .map{|k,v| Hash[k, v.map(&:last)]}
like image 132
Arie Xiao Avatar answered Nov 15 '22 06:11

Arie Xiao


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]}
like image 30
Daniël Knippers Avatar answered Nov 15 '22 07:11

Daniël Knippers