Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group Array of Hashes by Key followed by values

Tags:

ruby

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 array of hashes to:

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

I've read similar articles such as this and Group array of hashes by key

However, most examples return the values as increment counts where I'm looking for actual separate 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 went wrong is how I'm trying to segment the values. Any direction would be appreciated!

like image 615
Stephen C Avatar asked Nov 22 '16 15:11

Stephen C


1 Answers

input.reduce { |e, acc| acc.merge(e) { |_, e1, e2| [*e2, *e1] } }
#⇒ {:name=>["sam", "max", "joe"],
#   :animal=>["dog", "cat", "snake"],
#   :gender=>["male", "female", "male"]}
like image 130
Aleksei Matiushkin Avatar answered Sep 28 '22 04:09

Aleksei Matiushkin