Search code examples
functional-programmingtupleserlangmapselixir

Spanning repeatable keys


from such:

[
  {"Caerus1", "Ramses Refiner"},
  {"Caerus1", "Jupiter Refiner"},
  {"Caerus1", "Jupiter Other"},
  {"Caerus1", "Trader 13"},
  {"Caerus1", "Cathode Supplier 4"},
  {"Dionysus3", "Cathode Supplier 4"},
  {"Dionysus3", "Ramses Refiner"},
  {"Dionysus3", "Trader 13"},
  {"Dionysus3", "Jupiter Refiner"},
  {"Dionysus3", "Jupiter Other"},
  {"Prometheus2", "Jupiter Other"},
  {"Prometheus2", "Ramses Refiner"},
  {"Prometheus2", "Trader 13"},
  {"Prometheus2", "Cathode Supplier 4"},
  {"Prometheus2", "Jupiter Refiner"}
]

I'd like to achieve this:

[
  {"Caerus1" => ["Ramses Refiner", "Jupiter Refiner", "Jupiter Other", "Trader 13", "Cathode Supplier 4"]},
   .
   .
   .
]

So basically converting these tuples into a map with unique key - so it doesn't repeat (that I can do easily) the hard part is making a list of the 2nd element strings.

Thanks in advance


Solution

  • In Elixir it's quite easy with Enum.group_by/3:

    iex> Enum.group_by(values, fn {key, _} -> key end, fn {_, value} -> value end)
    %{
      "Caerus1" => ["Ramses Refiner", "Jupiter Refiner", "Jupiter Other",
       "Trader 13", "Cathode Supplier 4"],
      "Dionysus3" => ["Cathode Supplier 4", "Ramses Refiner", "Trader 13",
       "Jupiter Refiner", "Jupiter Other"],
      "Prometheus2" => ["Jupiter Other", "Ramses Refiner", "Trader 13",
       "Cathode Supplier 4", "Jupiter Refiner"]
    }