Elixir Enum Sorting
Sorting rearranges a collection into an order, such as smallest to largest. Enum provides sort functions that return a new sorted list and leave the original list unchanged.
Sort orders a list both ways
Enum.sort puts the scores from smallest to largest. The :desc option reverses that order, and the original list stays as it was.
scores = [320, 180, 450, 260]
IO.inspect(Enum.sort(scores))
IO.inspect(Enum.sort(scores, :desc))
IO.inspect(scores)Sort by orders items by a computed key
The key function measures each word with String.length. The words come out shortest first, and longest first with :desc.
words = ["banana", "fig", "cherries", "plum"]
IO.inspect(Enum.sort_by(words, fn w -> String.length(w) end))
IO.inspect(Enum.sort_by(words, fn w -> String.length(w) end, :desc))Min by and max by pick one item by key
Min_by returns fig, the word with the smallest length. Max_by returns cherries from the words and 180 as the smallest price under an identity key.
words = ["banana", "fig", "cherries", "plum"]
IO.puts(Enum.min_by(words, fn w -> String.length(w) end))
IO.puts(Enum.max_by(words, fn w -> String.length(w) end))
prices = [320, 180, 450]
IO.puts(Enum.min_by(prices, fn p -> p end))Example
names = ["Marta", "Jo", "Sebastian", "Ana"]
IO.inspect(Enum.sort(names))
IO.inspect(Enum.sort_by(names, fn n -> String.length(n) end))
IO.puts(Enum.min_by(names, fn n -> String.length(n) end))
IO.puts(Enum.max_by(names, fn n -> String.length(n) end))Key points
- Sort: Enum.sort returns a new list in ascending order by default.
- Descending: Enum.sort with :desc returns the list from largest to smallest.
- Sort by: Enum.sort_by sorts items by a key that its function computes for each item.
- Key function: the key function returns the value that items are compared by.
- Smallest by key: Enum.min_by returns the item with the smallest key.
- Largest by key: Enum.max_by returns the item with the largest key.
In this example, Enum.sort orders the names alphabetically. Enum.sort_by orders the same names by length instead, from Jo up to Sebastian. Enum.min_by and Enum.max_by then pick out those two extremes directly.
Note
sorting returns a new list, so the input list keeps its original order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Enum.sort([30, 5, 20], :desc) return?