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

Article autor
September 9, 2025
How to group and count occurrences of values in Elixir's list
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.

Table of contents

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}

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

Manually update Apollo cache after GraphQL mutation

Ensuring that GraphQL mutations properly update your Apollo client's cache can be a bit tricky - here's how to manually control that.

How to create and use custom shell commands?

Each of us had a situation, where we had to invoke a few, same commands each time. Making it once is not that problematic, but when we are supposed to repeat given operations, it may be better just to create one function that will handle it all.

Implicit try in Elixir

In the world of Elixir programming, there are numerous features and syntactic constructs that contribute to the language's elegance and expressiveness. One such hidden gem is the concept of "implicit try".