1

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?

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

Comments

1

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"}]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.