All posts

Sort a list of maps by key value

 elixir

Suppose you have a list of maps that you need to sort by a specific key in each of the maps, you can do so using elixir’s Enum module, Enum.sort_by/3.

This function requires an enum and callback function and optionally accepts a third sorter argument, like :asc and :desc. The sorter will use :asc by default.

The callback function passed to the argument needs to return the value that is being sorted on and sort_by will do the rest.

To sort by one key in ascending order:

l = [%{payment: 34, tip: 5}, %{payment: 21, tip: 6}, %{payment: 10, tip: 5}]

Enum.sort_by(l, fn(li) -> li.payment end)
=> [%{payment: 10, tip: 5}, %{payment: 21, tip: 6}, %{payment: 34, tip: 5}]

To sort by one key in descending order:

l = [%{payment: 34, tip: 5}, %{payment: 34, tip: 4}, %{payment: 21, tip: 7}, %{payment: 21, tip: 6}, %{payment: 10, tip: 5}]

Enum.sort_by(l, fn(li) -> li.payment end, :desc)
=> [%{payment: 34, tip: 5}, %{payment: 21, tip: 6}, %{payment: 10, tip: 5}]

To sort by multiple keys, return a tuple from the callback function:

l = [
  %{payment: 34, tip: 5},
  %{payment: 34, tip: 4},
  %{payment: 21, tip: 7},
  %{payment: 21, tip: 6},
  %{payment: 10, tip: 5}
]

Enum.sort_by(l, fn(li) -> {li.payment, li.tip } end)
=> [
  %{payment: 10, tip: 5},
  %{payment: 21, tip: 6},
  %{payment: 21, tip: 7},
  %{payment: 34, tip: 4},
  %{payment: 34, tip: 5}
]

If you enjoyed this elixir post you might also enjoy Reading pdf text using Elixir

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).