Reputation: 7373
I have a list of strings that I want to order in two ways.
Upvotes: 22
Views: 27196
Reputation: 54684
To sort a list of strings alphabetically, you can just use Enum.sort/1
, which will order items by their default order (which is alphabetic ordering for strings).
iex> Enum.sort(["b", "aaa", "cc"])
["aaa", "b", "cc"]
To sort a list by a different property, such as string length, you can use Enum.sort_by/2
, which takes a mapper function as second argument. The values will then be sorted by the result of this function applied to each element.
iex> Enum.sort_by(["b", "aaa", "cc"], &String.length/1)
["b", "cc", "aaa"]
Upvotes: 53