Quirrel4.53.0

types.Array.sort_reversed

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

Sorts the array in place in descending order: the order of sort with the two arguments of each compare swapped.

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

comparatorfunctionthe ascending order, as for sort: a negative result puts a after b; the default ordering when left out optional
...any repeats

Return value

This array.

Errors

The same as sort. The comparison between X and Y error names the pair in the swapped order.

Notes

arr.sort_reversed(cmp) gives the same result as arr.sort(@(a, b) cmp(b, a)), and arr.sort_reversed() the same as arr.sort(@(a, b) b <=> a). The comparator and the _cmp metamethods get the same calls as with that swapped comparator, but no script function swaps the arguments.

The sort is stable: elements that compare equal keep their relative order, as with reverse=True in Python. arr.sort() and then arr.reverse() puts equal elements in the reverse of their input order, so it gives the same result only when equal elements cannot be told apart, such as integers or strings.

Without a comparator, sort_reversed costs the same as sort: for 32 elements or more it is 6 to 7 times faster than arr.sort(@(a, b) b <=> a), and 2.3 times faster for 2 elements. For an order by a value of each element, use sortby_reversed.

As with sort, more than one argument is not an error: the comparator is then ignored and the default ordering is used.

Example

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

let players = [
  { name = "ann", score = 10 },
  { name = "bob", score = 30 },
  { name = "cid", score = 10 }
]
players.sort_reversed(@(x, y) x.score <=> y.score)   // ann stays before cid
println(", ".join(players.map(@(p) $"{p.name} {p.score}")))
Output:
3, 2, 1
bob 30, ann 10, cid 10

See also

sortSorts the array in place.
sortby_reversedSorts the array in place by the value that key returns for each element, in descending order.
reverseReverses the array in place.
arrayclass index