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