Quirrel4.53.0

types.Array.sortby_reversed

Method on every array
array.sortby_reversed(key: function): any

Sorts the array in place by the value that key returns for each element, in descending order.

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

keyfunctionkey(value, [index], [array]), called once for each element, in order, before the sort; not called for an array of one element or none

Return value

This array.

Errors

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

Notes

arr.sortby_reversed(key) gives the same order as arr.sort(@(a, b) key(b) <=> key(a)), and calls key once for each element as sortby does. The _cmp metamethods of the keys get the same calls as with that comparator.

The sort is stable: elements with equal keys keep their relative order. arr.sortby(@(v) -v.score) gives the same order for a numeric key, but it cannot negate a string, a bool or a null key; sortby_reversed sorts any keys that < can compare, and a null key sorts last.

It holds the same extra slots as sortby and costs the same.

Example

examples/types/array/sortby_reversed.nut
let players = [
  { name = "ann", score = 30 },
  { name = "bob", score = 10 },
  { name = "cid", score = 20 },
  { name = "dan", score = 10 }
]
players.sortby_reversed(@(p) p.score)   // bob stays before dan
println(", ".join(players.map(@(p) $"{p.name} {p.score}")))

let words = ["fig", "pear", "banana", "kiwi"]
words.sortby_reversed(@(w) w)           // a string key, which -w cannot give
println(", ".join(words))

let tasks = [{ id = 1 }, { id = 2, due = 5 }, { id = 3, due = 9 }]
tasks.sortby_reversed(@(t) t?.due)      // a null key sorts last
println(", ".join(tasks.map(@(t) t.id.tostring())))
Output:
ann 30, cid 20, bob 10, dan 10
pear, kiwi, fig, banana
3, 2, 1

See also

sortbySorts the array in place by the value that key returns for each element.
sort_reversedSorts the array in place in descending order: the order of sort with the two arguments of each compare swapped.
arrayclass index