18
votes

I have a list of strings that I want to order in two ways.

  1. Alphabetically
  2. By string length
1
What do you mean by without looping? The sorting operation needs to traverse through the list. In any case, maybe Enum.sort/2 is what you are looking for? - José Valim
@JoséValim You're right. I edited the question so it doesn't mislead. The Enum module has all I need. Can you post that as an answer? - Mauricio Moraes

1 Answers

43
votes

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"]