Hash into grouped array

2019-05-10 18:14发布

问题:

im not very experienced in ruby, so im struggling to format a piece of data.

I have this hash, wich contains some keys that have the same value, ex:

{"key" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value1", "key5" => "value2" ..}

I'm trying to turn this into, an array containing the keys grouped by the values

 [["key","key4"],["key2","key5"],["key3"]]

Any help would be appreciated.

回答1:

new_hash = {}
hash.each do |key, value|
  new_hash[value] ||= []
  new_hash[value] << key
end
array = new_hash.values # => [["key", "key4"], ["key2", "key5"], ["key3"]]


回答2:

hash = {
  "key" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" => "value1",
  "key5" => "value2"
}

hash.group_by { |key, value| value }.values.map { |pairs| pairs.map &:first }

# => [["key", "key4"], ["key2", "key5"], ["key3"]]


回答3:

hash.group_by{|k,v| v}.map{|k,v| v.reduce([]){|res,n| res << n.first}}


标签: ruby arrays hash