"dog", :gender => "male"...">

A group array of key hashes followed by values

Assuming I have the following dataset

[ 
  {
    :name => "sam",
    :animal => "dog",
    :gender => "male"
  }, {
    :name => "max",
    :animal => "cat",
    :gender => "female"
  }, {
    :name => "joe",
    :animal => "snake",
    :gender => "male"
  }    
]

How would you group the hash array:

{
  :name => ["sam", "max", "joe"]
  :animal => ["dog", "cat", "snake"]
  :gender => ["male", "female", "male"]
}

I have read related articles such as this and Group Hashes by Key

However, most examples return values ​​in the form of increment counts, where I look for the actual individual values.

My attempt

keys = []
values = []

arr.each do |a|
  a.each do |k, v|
    keys << k
    #this is where it goes wrong and where I'm stuck at
    values << v
  end
end

keys = keys.uniq

I understand where I made a mistake, this is how I try to segment values. Any direction will be appreciated!

+4
source share
2 answers
input.reduce { |e, acc| acc.merge(e) { |_, e1, e2| [*e2, *e1] } }
#⇒ {:name=>["sam", "max", "joe"],
#   :animal=>["dog", "cat", "snake"],
#   :gender=>["male", "female", "male"]}
+4
source

several approaches

data.each_with_object({}){ |i,r| i.each{ |k,v| (r[k] ||= []) << v } }
data.flat_map(&:to_a).each_with_object({}){ |(k,v), r| (r[k] ||= []) << v }
data.flat_map(&:to_a).group_by(&:first).inject({}){ |r, (k,v)| r[k] = v.map(&:last); r }
+1
source

Source: https://habr.com/ru/post/1661597/


All Articles