Returns a copy of the indicated treelike object with the keys sorted. The sort is performed with the default lexicographic Unicode sort order provided by JavaScript’s Array.sort() method.
$ cat capitals.yaml
Japan: Tokyo
Turkey: Ankara
Australia: Canberra
Spain: Madrid
$ ori @sort capitals.yaml
Australia: Canberra
Japan: Tokyo
Spain: Madrid
Turkey: Ankara
Options
The @sort
built-in takes an optional options
argument. This can take the form of an object containing any or all of:
compare
. A function that compares two arguments. This uses the same definition as the JavaScript Array sort() method. If omitted, items are converted to strings and sorted as strings.sortKey
. A function evaluated for each entry in the tree to determine a sort key. See below.
The default compare
function sorts text strings by their Unicode character values. If you are sorting things for display to end users, consider using @naturalOrder as the compare
function.
As a shorthand, if you supply a function as the second argument to @sort
, it will be used as the sortKey
function.
To reverse the sort order, apply @sort
and then @reverse.
Sort keys
As shown in the example above, by default @sort
sorts a tree by its keys. You can supply a sortKey
option that returns a different value that the tree should be sorted by. This function will be called with three arguments: the value being considered, the key for that value, and the tree being sorted. You don’t have to use all three arguments.
$ cat capitals.yaml
Japan: Tokyo
Turkey: Ankara
Australia: Canberra
Spain: Madrid
$ ori "@sort capitals.yaml, (value, key, tree) => value"
Turkey: Ankara
Australia: Canberra
Spain: Madrid
Japan: Tokyo
Functional form
@sort
has a functional form called @sortFn
that accepts just the options argument of @sort
and returns a function that can be applied to a tree to sort it. This is intended for use in content pipelines.
$ ori "capitals.yaml → @sortFn((value) => value)"
Turkey: Ankara
Australia: Canberra
Spain: Madrid
Japan: Tokyo