β οΈ This post links to an external website. β οΈ
In this post, youβll learn how to sort a list of structs (or maps) by two dates.
TL;DR
Elixir official Enum.sort/2 docs tell you how to sort by a date using the
Datemodule, for example:iex> Enum.sort([~D[2024-05-05], ~D[2024-05-01], ~D[2024-05-03]], {:asc, Date})[~D[2024-05-01], ~D[2024-05-03], ~D[2024-05-05]]Using descendant order:
iex> Enum.sort([~D[2024-05-05], ~D[2024-05-01], ~D[2024-05-03]], {:desc, Date})[~D[2024-05-05], ~D[2024-05-03], ~D[2024-05-01]]But, what when you need to use a key from a map?
Elixirβs Enum.sort_by/3 accepts a mapper function to extract the said value. From the docs:
This function maps each element of the enumerable using the provided mapper function. The enumerable is then sorted by the mapped elements using the sorter, which defaults to :asc and sorts the elements ascendingly.
continue reading on rlopzc.com
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.