All posts

Elixir List count of each unique element

 elixir

There may come a time where you need to get a count of how many times a specific element occurs in a List. It might be needed for reporting, or to show to a user in an admin dashboard.

To accomplish this in Elixir you can use the Enum.frequencies/1 function. This function will take one argument, the enumerator, and return map with each unique element and itโ€™s occurence count.

Enum.frequencies(["football", "baseball", "baseball", "hockey", "baseball"])
=> %{"baseball" => 3, "football" => 1, "hockey" => 1}

Further reading:

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).