我有一个以这种方式完成的数组
[{"g"=>1, "f"=>"01"}, {"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}, {"g"=>3, "f"=>"04"}, {"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]
我必须分成具有相同"g"
值的组,例如
[{"g"=>1, "f"=>"01"}],
[{"g"=>2, "f"=>"02"}, {"g"=>2, "f"=>"03"}],
[{"g"=>3, "f"=>"04"}],
[{"g"=>4, "f"=>"05"}, {"g"=>4, "f"=>"06"}]
我尝试a.map{|a| a['g']}.uniq
找到所有唯一的"g"
,然后使用each
函数将结果数组应用于select
到第一个数组,但产生没有结果。有人知道如何将数组分组?
答案 0 :(得分: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"}]
# }
然后,为了获得解决方案,请致电grouped.values
答案 1 :(得分:1)
我更喜欢@ Max使用group_by
,但希望展示一种效率相似的替代品。两者都产生一个哈希,然后提取它的值。
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"}]]