I have a hash that looks like this:
{"a" => [1, 2, 3], "b" => [4, 5, 6], "c" => [3, 4, 5], "d" => [7, 2, 3]}
What I want to do is to make a hash of all existing values with an array of all keys that included it, e.g. turn the above into this:
{1 => ["a"], 2 => ["a", "d"], 3 => ["a", "c", "d"], 4 => ["b", "c"]}
I do prefer @Jikku's solution, but there's always another way. Here's one. [Edit: I see this is very close to @Chris's solution. I will leave it for the last line, which is a little different.]
Code
Example
Explanation
For
h
above:Try this:
An alternate solution:
Or:
The idea here is that we use
Array#product
to create a list of inverted single key-value pairs:Group them by the value of the first item in each pair:
And then convert the values to a list of the last values in each pair: