Count Occurrences of Elements in List
The Enum Module in Elixir has the frequencies/1
function, which is useful for counting the occurrences of each element in a list.
> Enum.frequencies(["dog", "cat", "dog", "bird", "dog", "cat"])
%{"bird" => 1, "cat" => 2, "dog" => 3}
There's also frequencies_by/2
, where the 2nd argument is a function that normalizes the element/key before counting.
> Enum.frequencies_by(["a", "b", "a", "C", "A"], fn key ->
String.upcase(key)
end)
%{"A" => 3, "B" => 1, "C" => 1}
https://devdocs.io/elixir~1.17/enum#frequencies/1
Tweet