I have a list of strings that I want to order in two ways.
The length() function returns the length of the list that is passed as a parameter.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With