How to use Enum.group_by with multi columns

I know how to use Enum.group_by with one column, but I’m not sure how to use it with multi columns.

Following example is group_by(id).

input = %{
  "1" => [
    %{id: "1", seq: "1", lang: "Elixir", name: "Bob"},
    %{id: "1", seq: "1", lang: "Java", name: "Bob"},
    %{id: "1", seq: "2", lang: "Ruby", name: "Bob"}
  ],
  "2" => [
    %{id: "2", seq: "1", lang: "Elixir", name: "Tom"},
    %{id: "2", seq: "2", lang: "C#", name: "Tom"}
  ],
  "3" => [
    %{id: "3", seq: "1", lang: "Python", name: "Dave"},
    %{id: "3", seq: "1", lang: "Java", name: "Dave"},
    %{id: "3", seq: "2", lang: "Ruby", name: "Dave"}
  ],
  "4" => [%{id: "4", seq: "1", lang: "Python", name: "Jane"}]
}

I would like to make group_by with id & seq, in this case.
Is there any idea for it?

1 Like

Can you please post your expected output?

You can do: Enum.group_by(collection, &{&1.id, &1.seq})

4 Likes

Thank you so much. It worked as I expected.

2 Likes