Antonio Cipolla
Antonio Cipolla

Reputation: 152

ruby array of hash with same value

I have an array done in this way

[{"g"=>1, "f"=>"01"}, {"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}, {"g"=>3, "f"=>"04"}, {"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]

and I have to split into groups with the same value of "g", like

[{"g"=>1, "f"=>"01"}],
[{"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}],
[{"g"=>3, "f"=>"04"}],
[{"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]

I tried to a.map{|a| a['g']}.uniq to find all the unique "g" and then to use each function to the resulting array to apply a select to the first array, but produce no result. Some one knows how to divide the array in groups?

Upvotes: 1

Views: 151

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

I prefer @Max's use of group_by, but wish to show an alternative that should be similar in efficiency. Both produce a hash and then extract its values.

arr = [{"g"=>1, "f"=>"01"}, {"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"},
       {"g"=>3, "f"=>"04"}, {"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]

arr.each_with_object({}) { |f,h| (h[f["g"]] ||= []) << f }.values
   #=> [[{"g"=>1, "f"=>"01"}],
   #    [{"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}],
   #    [{"g"=>3, "f"=>"04"}], 
   #    [{"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]]

Upvotes: 1

max pleaner
max pleaner

Reputation: 26768

input = [{"g"=>1, "f"=>"01"}, {"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}, {"g"=>3, "f"=>"04"}, {"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]

grouped = input.group_by { |hash| hash["g"] }
# => {
#      1=>[{"g"=>1, "f"=>"01"}],
#      2=>[{"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}],
#      3=>[{"g"=>3, "f"=>"04"}],
#      4=>[{"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]
#    }

Then to get your solution you call grouped.values

Upvotes: 4

Related Questions