Does elixir Enum or any other module have group_by function similar to ruby's group_by

StackOverflow https://stackoverflow.com/questions/21818069

  •  12-10-2022
  •  | 
  •  

سؤال

Ruby has this awesome method group_by for Enumerable. Does Elixir have something similar? I could not find this functionality on the Enum module. Thanks

هل كانت مفيدة؟

المحلول 2

Here is an example of group_by/3 in Enum module.

Grouping an array of strings based on its length:

iex(12)> ["ant", "buffalo", "cat", "dingo"] |>  Enum.group_by(&String.length/1)

         %{3 => ["cat", "ant"], 5 => ["dingo"], 7 => ["buffalo"]}

From the docs:

Splits collection into groups based on a fun.

The result is a dict (by default a map) where each key is a group and each value is a list of elements from collection for which fun returned that group. Ordering is not necessarily preserved.

نصائح أخرى

Not yet. We haven't added it because we were waiting on maps. It will be added to the v0.13 branch. :)

* UPDATE *
For anyone who didn't notice the comment below, it has now been added.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top