Enum sort

elixir, sorting, enum – Sep 23 2018

Some of the basics of sorting with the Enum module.

• • •

If you have just a list of strings you can sort on the list using Enum.sort/1.

users = ["tony", "sam", "alex"]
# ["alex", "sam", "tony"]

Sort with a comparison function

If you need to sort by a property in a map you can use Enum.sort/2 and pass in a comparison function.

users =  [%{name: "tony"}, %{name: "same"}, %{name: "alex"}]
Enum.sort(users, &(&1.name < &2.name))
# [%{name: "alex"}, %{name: "same"}, %{name: "tony"}]

Sort by

Going through the documentation you will come across Enum.sort_by/3. By using this you will have a similar result to the example above.

users =  [%{name: "tony"}, %{name: "same"}, %{name: "alex"}]
Enum.sort_by(users, fn user -> user.name end)
# [%{name: "alex"}, %{name: "same"}, %{name: "tony"}]

According to the documentation

sort_by/3 differs from sort/2 in that it only calculates the comparison value for each element in the enumerable once instead of once for each element in each comparison. If the same function is being called on both elements, it’s also more compact to use sort_by/3.

sort_by/3 is more performant for large sets of data when you have a function you want to compare.

Source: Elixir Documentation

Follow on Twitter
Follow on Github