Enum sort
Some of the basics of sorting with the Enum module.
We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
If you have just a list of strings you can sort on the list using Enum.sort/1
.
users = ["tony", "sam", "alex"]
Enum.sort(users)
# ["alex", "sam", "tony"]
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"}]
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 fromsort/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.