How to group and count occurrences of values in Elixir's list

If you ever had to count occurrences of values in Elixir's list, this short post might be helpful for you!
Let's assume that the input contains a list of people names:
people = [
%{name: "John"},
%{name: "Tom"},
%{name: "John"},
%{name: "David"}
]
Our goal here is to count occurrences of names so that in the end we'll get this summary:
%{"David" => 1, "John" => 2, "Tom" => 1}
In Elixir, it's super easy! You can use Enum.frequencies_by/2 to achieve that in a simple one-liner:
iex > Enum.frequencies_by(people, & &1.name)
%{"David" => 1, "John" => 2, "Tom" => 1}
Work with a team that keeps learning and building better software every day.
Related posts
Dive deeper into this topic with these related posts
You might also like
Discover more content from this category
It's easy to contain absolute positioned elements. Things get a little trickier when you want to contain a fixed positioned element without changing its stylings.
There are a bunch of operations you may want to perform before the rendered response in conn is sent to the client, such as minification. In this post I'll show you how to do it easily.
Sooner or later you'll have to change the null constraint in one of your DB relations. How to do it easily in Ecto?
