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 a go 1 hash

  • b should array of {c => , d =>}

  • d should array

  • d same value of c go 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

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -