Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 48 ยท Enumerables and Data Processing

Ranges, Sorting and Custom Ordering

Learn Elixir ranges with steps, Enum.sort and sort_by, sorting by several keys, descending order, comparing dates with Date.compare and how term ordering works.

Two small tools show up in almost every Elixir program that handles collections: ranges, which describe a run of integers without building a list, and sorting, which puts data into the order a person wants to see. Both look simple, and both have a few details that surprise newcomers: a range with a step, a descending sort, sorting by two fields at once, or sorting dates, which do not compare correctly with < and >.

This lesson builds on the Enum module and operators and comparison. You will learn how ranges are stored, how Enum.sort/2 and Enum.sort_by/3 work, how to sort by several keys, and how to hand a module such as Date to the sorter.

Elixir is not installed on this site, so the Elixir code below is read-only. The runnable examples are JavaScript stand-ins that copy the idea of each technique. They are not Elixir, and the exact output of real Elixir may differ in formatting.

Ranges

A range is written first..last and includes both ends:

ELIXIR
range = 1..10
Enum.to_list(range)    # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enum.sum(1..100)       # 5050
5 in 1..10             # true
Range.size(1..10)      # 10

A range is not a list. It is a small struct holding the first value, the last value and a step, so 1..1_000_000_000 costs the same memory as 1..3. Functions in Enum walk it one number at a time, and Stream can walk it lazily (see lazy processing with Stream).

Steps

Add //step to skip numbers:

ELIXIR
Enum.to_list(1..10//3)     # [1, 4, 7, 10]
Enum.to_list(0..20//5)     # [0, 5, 10, 15, 20]
Enum.to_list(10..1//-3)    # [10, 7, 4, 1]

The step must be an integer other than zero. A positive step with first > last gives an empty range, and a negative step with first < last does as well:

ELIXIR
Enum.to_list(1..5//-1)     # []
Enum.to_list(5..1//1)      # []

Older code often wrote 10..1 and relied on the range counting down. Modern Elixir treats that as a legacy shortcut. Write the step explicitly (10..1//-1) so the direction is obvious, and so a bug where the bounds are accidentally swapped gives an empty range instead of a silent countdown.

Reading a range

first The value where the range starts.
last The inclusive end of the range.
step How far each move goes, after //.

1..10//3 starts at 1, ends by 10 and moves 3 at a time.

1 / 2

Ranges are also handy for slicing and for guards:

ELIXIR
Enum.slice([10, 20, 30, 40, 50], 1..3)   # [20, 30, 40]
String.slice("elixir", 0..2)             # "eli"

def grade(score) when score in 90..100, do: "A"
def grade(score) when score in 80..89, do: "B"

The in operator works in a guard only when the right side is a literal range or list.

Sorting basics

Enum.sort/1 sorts by the standard ordering of Elixir terms and returns a new list. The original is never changed, because data is immutable:

ELIXIR
Enum.sort([3, 1, 2])                # [1, 2, 3]
Enum.sort(["pear", "apple", "fig"]) # ["apple", "fig", "pear"]
Enum.sort([3, 1, 2], :desc)         # [3, 2, 1]
Enum.sort([3, 1, 2], :asc)          # [1, 2, 3]

You can also pass a function. It receives two elements and returns true when the first may stay in front of the second:

ELIXIR
Enum.sort(["pear", "apple", "fig"], fn a, b -> String.length(a) <= String.length(b) end)
# ["fig", "pear", "apple"]

Use <= rather than < in such a function. With <, two equal elements would swap places, and the sort would no longer be stable. Enum.sort/2 keeps equal elements in their original order only when your function returns true for equal pairs.

Sorting strings

Strings compare byte by byte, so uppercase letters come before lowercase ones ("Zebra" < "apple" is true). To sort the way a person expects, sort by a normalized key:

ELIXIR
Enum.sort_by(["banana", "Apple", "cherry"], &String.downcase/1)
# ["Apple", "banana", "cherry"]

sort_by: sort by a computed key

Most real data are maps or structs, and you rarely sort them as a whole. Enum.sort_by/3 takes a function that extracts the key to compare:

ELIXIR
people = [
  %{name: "Mia", age: 31},
  %{name: "Leo", age: 24},
  %{name: "Ana", age: 31}
]

Enum.sort_by(people, & &1.age)
# [%{name: "Leo", age: 24}, %{name: "Mia", age: 31}, %{name: "Ana", age: 31}]

The function is called once per element, and then the keys are sorted. That is cleaner and often faster than writing a two-argument comparison. Mia stays ahead of Ana because the sort is stable.

For descending order, pass :desc as the third argument:

ELIXIR
Enum.sort_by(people, & &1.age, :desc)

Related helpers pick one element without sorting everything: Enum.min_by/2, Enum.max_by/2, Enum.min/1 and Enum.max/1.

Sorting by several keys

Tuples are compared element by element, left to right. So to sort by age and then by name, return a tuple as the key:

ELIXIR
Enum.sort_by(people, &{&1.age, &1.name})
# Leo (24), Ana (31), Mia (31)

The tuple {31, "Ana"} sorts before {31, "Mia"} because the first elements tie and the second ones decide.

Mixing directions (age descending, name ascending) is where people get stuck, because :desc applies to the whole key. There are two clean answers. For numbers you can negate the part that should go the other way:

ELIXIR
Enum.sort_by(people, &{-&1.age, &1.name})
# Ana (31), Mia (31), Leo (24)

For anything else, do two stable sorts, the least important key first:

ELIXIR
people
|> Enum.sort_by(& &1.name)
|> Enum.sort_by(& &1.age, :desc)

Because each pass is stable, the second pass keeps the name order inside each age group.

JS Multi-key sort, as a JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Term ordering

Enum.sort/1 works on any mix of values, because every Elixir term has a place in one global order:

Text
number < atom < reference < function < port < pid < tuple < map < list < bitstring

Integers and floats compare by value. Tuples compare by size first, then element by element. Lists compare element by element, and bitstrings (including strings) compare byte by byte:

ELIXIR
Enum.sort([:b, 2, "a", {1}, [0], 1.5])
# [1.5, 2, :b, {1}, [0], "a"]

You will rarely depend on cross-type ordering, but it explains why sorting a mixed list never raises an error.

Dates need a module

Dates, times and datetimes are structs, and structs are maps. Comparing two maps with < compares their keys and values in a way that has nothing to do with the calendar. Always use the module's own compare/2, which returns :lt, :eq or :gt:

ELIXIR
Date.compare(~D[2026-03-01], ~D[2025-12-31])   # :gt
Date.before?(~D[2025-12-31], ~D[2026-03-01])   # true

Enum.sort/2 and Enum.sort_by/3 accept such a module directly in place of :asc or :desc:

ELIXIR
dates = [~D[2026-03-01], ~D[2024-07-15], ~D[2025-12-31]]

Enum.sort(dates, Date)            # [~D[2024-07-15], ~D[2025-12-31], ~D[2026-03-01]]
Enum.sort(dates, {:desc, Date})   # newest first
Enum.min(dates, Date)             # ~D[2024-07-15]

events = [%{title: "Launch", on: ~D[2026-03-01]}, %{title: "Kickoff", on: ~D[2024-07-15]}]
Enum.sort_by(events, & &1.on, {:desc, Date})

The same works for Time, DateTime, NaiveDateTime and Decimal. The next lesson covers the ~D sigil: Sigils and Regular Expressions.

JS Compare dates the right way

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Enum.to_list(1..10//3) return?

    The step 3 moves 1 to 4 to 7 to 10. The last value is inclusive, and 10 is reached exactly.
  2. 2. How much memory does the range 1..1_000_000_000 use?

    A range is a small struct. Values are produced one at a time when Enum or Stream walks it.
  3. 3. How do you sort a list of people by age descending?

    sort_by takes a key function and an optional sorter such as :desc. Reversing only helps if the list was already sorted ascending.
  4. 4. Why should you sort dates with Date.compare/2 (or pass Date as the sorter) instead of using < and >?

    Structural comparison of maps looks at keys and values in an internal order. Only Date.compare/2 knows that a year outranks a month and a month outranks a day.

Summary

  • A range first..last//step stores three numbers, so it is cheap however long it is; write the step explicitly when counting down.
  • Enum.sort/2 takes :asc, :desc, a comparison function or a module such as Date; it never changes the original list.
  • Enum.sort_by/3 sorts by a computed key and is the everyday tool for maps and structs.
  • Tuple keys sort by several fields; negate numbers or chain two stable sorts to mix directions.
  • All terms have one global order, so sorting mixed values never raises.
  • Compare dates and times with their module's compare/2, never with < or >.

Next, put patterns to work on text: Sigils and Regular Expressions.