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!

Table of contents

    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}
    Download our ebook
    Sign to our Newsletter
    Szymon Soppa Web Developer
    Szymon Soppa Curiosum Founder & CEO

    Read more
    on #curiosum blog

    Debugging Elixir Code: The Definitive Guide

    Every application contains bugs, and even if it doesn't, it will. And even if you're not a notorious bug producer and your code quality is generally good, the conditions programmers work in are often suboptimal - you will often find yourself pulling your hair out over code written years ago by someone no longer involved in your project.

    Top Elixir Learning Media & Resources in 2022

    Regardless of whether you've only just heard of the Elixir programming language and would like to learn it, or if you're a seasoned developer with years of experience, you need adequate learning resources to ensure steady progress in your career - and just equally as important is the need to be up to date with what's new & trending in the functional