{key, value} list groupping

133 views
Skip to first unread message

Nokan Emiro

unread,
Jul 11, 2016, 12:19:36 PM7/11/16
to elixir-lang-talk
Hi,

I have a recuring pattern that I feel could be done better.  There's a list of 2-tuples where the tuples are {key, value} pairs.  The same key can be there more than once in the list.  I want to transform it into a map where the keys are the keys from the tuples and the values become lists of all the values coming from the tuples with the same key.  (The order in the list doesn't matter.)

For examle:

      list_of_tuples = [{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}, {5, 6}]
      --> %{1 => [2, 3, 4], 2 => [3, 4], 3 => [4], 5 => [6]}

I used to do this with the following transformation:

      list_of_tuples
      |> Enum.group_by(&(elem(&1,0)))
      |> Enum.map(fn {k, v} -> {k, Enum.map(v, &(elem(&1, 1)))} end)
      |> Enum.into(%{})

Is there any better or more elegant way?


José Valim

unread,
Jul 11, 2016, 12:31:01 PM7/11/16
to elixir-l...@googlegroups.com
In Elixir v1.3 you can do: Enum.group_by(list_of_tuples, &elem(&1, 0), &elem(&1, 1)).



José Valim
Skype: jv.ptec
Founder and Director of R&D

--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-talk/4a49c836-c643-4eca-8892-6a7a0f5e2ecb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages