ruby - How to merge hash of arrays? -
i have array:
[  {a => 1, b => { c => 1, d => 1}},  {a => 1, b => { c => 1, d => 2}},  {a => 1, b => { c => 2, d => 2}},  {a => 2, b => { c => 1, d => 1}}, ] i want change this:
[  {a => 1, b => [{ c => 1, d => [1, 2]}, { c => 2, d => [2]}]},  {a => 2, b=> [ { c=> 1, d => [1] } ]} ] rules/requirements:
- hashes of same value of - ago 1 hash
- bshould array of- {c => , d =>}
- dshould array
- dsame value of- cgo same array
here solution. explicit, not generalize other hash structures.
hashes = [  {:a => 1, :b => { :c => 1, :d => 1}},  {:a => 1, :b => { :c => 1, :d => 2}},  {:a => 1, :b => { :c => 2, :d => 2}},  {:a => 2, :b => { :c => 1, :d => 1}}, ]  a_values = {} hashes.each |hash|   a_value = hash[:a]   a_values[a_value] ||= {}    c_value = hash[:b][:c]   a_values[a_value][c_value] ||= { :c => c_value, :d => [] }    d_value = hash[:b][:d]   a_values[a_value][c_value][:d].push(d_value) end  # aggregate results results = a_values.map |a_value, c_hashes|   b_arr = c_hashes.map { |c_value, c_hash| c_hash }   { :a => a_value, :b => b_arr } end and here output:
[   {:a=>1, :b=>[{:c=>1, :d=>[1, 2]}, {:c=>2, :d=>[2]}]},    {:a=>2, :b=>[{:c=>1, :d=>[1]}]} ] 
Comments
Post a Comment