Count Occurrences in Elixir
Elixir recently introduced an useful couple of functions to count how many times a value appears in an Enumerable. It comes in two formats: frequencies/1 and frequencies_by/2. Here's an example:
iex> [
...> %{name: "Falcon", power: "Flight"},
...> %{name: "Titan Spirit", power: "Flight"},
...> %{name: "Atom Claw", power: "Strength"},
...> %{name: "Electro", power: "Electricity Control"},
...> %{name: "Loki Brain", power: "Telekinesis"},
...> ] |> Enum.frequencies_by(& &1.power)
%{
"Electricity Control" => 1,
"Flight" => 2,
"Strength" => 1,
"Telekinesis" => 1
}
Tweet