Home > Back-end >  How can I split Hash keys into 2 or more arrays based on keys which contain same values?
How can I split Hash keys into 2 or more arrays based on keys which contain same values?

Time:02-19

Say I made a Hash like this: ["ab" => "a", "ac" => "a", "cd" => "c", "ce" => "c", "df" => "d"]

and I need to split this into 3 arrays like these: ["ab", "ac"], ["cd", "ce"], ["df"]. Split my Hash into 3 arrays based on keys which has same values.

How can I do this?

CodePudding user response:

you can use group by on a hash and group by the values this will return a hash with the value as a key and all hashes with the same value in an array then transform the values and take the first element in each array of that value (wich would be the key of the original objects)

hash.group_by { |key, value| value }.transform_values(&:first).values

[1] pry(main)> {"ab" => "a", "ac" => "a", "cd" => "c", "ce" => "c", "df" => "d"}.group_by { |key, value| value }.transform_values(&:first).values
=> [["ab", "a"], ["cd", "c"], ["df", "d"]]

CodePudding user response:

Input

a={"ab" => "a", "ac" => "a", "cd" => "c", "ce" => "c", "df" => "d"}

Code

p a.group_by{|_,v|v}
   .values
   .map{|arr|arr.map(&:first)}

output

[["ab", "ac"], ["cd", "ce"], ["df"]]
  •  Tags:  
  • ruby
  • Related