Mauricio Moraes
Mauricio Moraes

Reputation: 7373

Sort List elements in Elixir Lang

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

  1. Alphabetically
  2. By string length

Upvotes: 22

Views: 27196

Answers (1)

Patrick Oscity
Patrick Oscity

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

Related Questions