Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash into grouped array

Tags:

arrays

ruby

hash

I'm not very experienced in ruby, so I'm struggling to format a piece of data.

I have this hash, which 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"]]
like image 426
tehplaceholder Avatar asked Aug 14 '26 05:08

tehplaceholder


2 Answers

new_hash = {}
hash.each do |key, value|
  new_hash[value] ||= []
  new_hash[value] << key
end
array = new_hash.values # => [["key", "key4"], ["key2", "key5"], ["key3"]]
like image 163
Andrew Marshall Avatar answered Aug 16 '26 23:08

Andrew Marshall


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"]]
like image 33
Matheus Moreira Avatar answered Aug 16 '26 23:08

Matheus Moreira