Skip to content

Sorts lists and record fields.

sort(xs:list|record, [desc=bool, cmp=(a, b) => bool]) -> list|record

The sort function takes either a list or record as input, ordering lists by value and record fields by field name. When sorting records, sort recursively sorts nested record fields, including records inside lists.

The list or record to sort.

When true, sorts the list in descending order.

The desc parameter only applies to lists. For records, fields are always sorted ascending by key name.

Defaults to false.

A binary lambda that receives two elements and returns a boolean indicating whether the first element should come before the second. This lets you define a custom sort order, for example to sort a list of records by a specific field.

The cmp parameter only applies to lists. When combined with desc=true, the comparison is reversed by swapping the arguments before passing them to the lambda.

from {xs: [1, 3, 2]}
xs = xs.sort()
{xs: [1, 2, 3]}
from {a: 1, c: 3, b: {y: true, x: false}}
this = this.sort()
{a: 1, b: {x: false, y: true}, c: 3}

Nested list element order is preserved unless the list itself is being sorted.

from {xs: [3, 1, 2]}
xs = xs.sort(desc=true)
{xs: [3, 2, 1]}

Sort records by a specific field using a custom comparator

Section titled “Sort records by a specific field using a custom comparator”
from {xs: [{v: 2, id: "b"}, {v: 1, id: "a"}, {v: 2, id: "c"}]}
xs = xs.sort(cmp=(a, b) => a.v < b.v)
{xs: [{v: 1, id: "a"}, {v: 2, id: "b"}, {v: 2, id: "c"}]}

Last updated: