Quirrel4.41.0

types.Array.sort

Method on every array
array.sort([comparator: function], ...): any

Sorts the array in place.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

comparatorfunctioncompares two elements; the default ordering when left out (see Notes) optional
...any repeats

Return value

This array.

Errors

Whatever comparator throws. Without a comparator, throws comparison between X and Y for a pair of elements neither numeric-with-numeric, string-with-string, nor both instances of a class (or tables) that defines _cmp.

Notes

comparator(a, b) must return a negative number when a sorts before b, a positive number when it sorts after, and 0 when they are equal, the same convention as _cmp.

Despite the trailing ... in the signature above, sort is not variadic: it takes zero or one real argument. Calling it with more than one extra argument does not throw, unlike findvalue; it silently falls back to the default ordering, as if comparator had been left out entirely.

Without a comparator, elements are compared the way < compares them: numbers by value, strings lexicographically, and a table or instance through its _cmp metamethod if it has one; anything else is a comparison between error.

sort is not a stable sort: elements that compare equal can still change their order relative to each other. Do not rely on the relative order of elements a comparator reports as equal.

Example

examples/types/array/sort.nut
let a = [3, 1, 2];
a.sort();                          // no comparator: default ascending order
println("a sorted =", ", ".join(a.map(@(v) v.tostring())));

let b = [3, 1, 2];
b.sort(function(x, y) { return y <=> x });   // one comparator: descending order
println("b sorted desc =", ", ".join(b.map(@(v) v.tostring())));

// two extra arguments: the comparator is silently ignored, default order wins
let c = [3, 1, 2];
c.sort(function(x, y) { return y <=> x }, "ignored");
println("c sorted (comparator ignored) =", ", ".join(c.map(@(v) v.tostring())));
Output:
a sorted = 1, 2, 3
b sorted desc = 3, 2, 1
c sorted (comparator ignored) = 1, 2, 3

See also

reverseReverses the array in place.
arrayclass index