Reference · Lists

sort

signature
sort(list | null) -> list

What it does

The items in ascending order, as a new list. Numbers (ints, floats and decimals together) order as numbers and strings by code point. The sort is stable: items that compare equal keep their order. There is no comparator and no descending flag; use sort_by for a key and reverse for descending. null counts as an empty list.

Examples

print(sort([3, 1, 2]))print(sort([2, 1.5, 1]))print(sort(["pear", "apple", "fig"]))print(reverse(sort([3, 1, 2])))
output
[1, 2, 3][1, 1.5, 2]["apple", "fig", "pear"][3, 2, 1]

Edge cases

print(sort([]), sort(null))let xs = [3, 1, 2]let s = sort(xs)print(xs, s)print(sort(["b", "B", "a", "A", "éa"]), sort(["10", "9", "100"]), sort([10, 9, 100]))print(sort_by(["Bob", "alice", "Carl"], lower))print(sort([1, 1.0]), sort([1.0, 1]), sort([3, 3, 1]))print(sort([2, dec("1.75"), 1]))
output
[] [][3, 1, 2] [1, 2, 3]["A", "B", "a", "b", "éa"] ["10", "100", "9"] [9, 10, 100]["alice", "Bob", "Carl"][1, 1.0] [1.0, 1] [1, 3, 3][1, 1.75m, 2]

Errors

An argument that is not a list or null is a runtime error, not an error value. Two items that do not order are a runtime error too: a string with a number, null, booleans, lists, maps, NaN, or a decimal with a float (convert one side first), in the browser as on the server; vec.argsort puts NaN last. A list of one item is never compared, so sort([null]) is [null].

this one fails
print(sort([1, "a"]))
output
line 1: `sort` cannot compare str with int

Lists compare item by item:

print(sort([[2, 1], [1, 9], [1, 2]]))
output
[[1, 2], [1, 9], [2, 1]]
this one fails
print(sort([dec("1"), 1.5]))
output
line 1: `sort` cannot compare float with dec: a dec is exact and a float is not, so convert one with dec(x) or float(x)

Chaining

In a pipeline sort takes the list and needs no arguments: xs | sort. Reverse it for descending, take from the front for the smallest few.

print([3, 1, 2] | sort | reverse)print([5, 3, 9, 1] | sort | take(2))print(["b", "a", "b"] | unique | sort | join(", "))
output
[3, 2, 1][1, 3]a, b

See also

sort_by, reverse, unique, min, max, vec.argsort

Thread
6Useful? Like it, or add to its thread below.

Thread 0 posts

On sort(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo