How to merge two arrays of hashes How to merge two arrays of hashes ruby ruby

How to merge two arrays of hashes


uniq would work if you concatenate the arrays in reverse order:

(b + a).uniq { |h| h[:key] }#=> [#     {:key=>1, :value=>"bar"},#     {:key=>1000, :value=>"something"},#     {:key=>2, :value=>"baz"}#   ]

It doesn't however preserve the order.


[a, b].map { |arr| arr.group_by { |e| e[:key] } }      .reduce(&:merge)      .flat_map(&:last)

Here we use hash[:key] as a key to build the new hash, then we merge them overriding everything with the last value and return values.


I would rebuild your data a bit, since there are redundant keys in hashes:

thin_b = b.map { |h| [h[:key], h[:value]] }.to_h#=> {1=>"bar", 1000=>"something"}thin_a = b.map { |h| [h[:key], h[:value]] }.to_h#=> {1=>"bar", 1000=>"something"}

Then you can use just Hash#merge:

thin_a.merge(thin_b)#=> {1=>"bar", 2=>"baz", 1000=>"something"}

But, if you want, you can get exactly result as mentioned in question:

result.map { |k, v| { key: k, value: v } }#=> [{:key=>1, :value=>"bar"}, #    {:key=>2, :value=>"baz"}, #    {:key=>1000, :value=>"something"}]