Sort modifier

Learn how to to sort the items of a collection.

This modifier sorts the elements of a collection based on a specified order and mode.

When sorting, this modifier uses the same comparison rules as the relational operators to ensure consistency in how it determines the order of two items. And, as with comparisons, attempting to sort a collection that contains elements that are not comparable will result in an error.

You can also use this modifier to sort maps. Although the keys are not used for sorting, they are preserved in the resulting map.

Syntax

The basic syntax for this modifier is as follows:

/*<collection>*/ sorted
Try in Playground

You can optionally specify an order and/or mode for sorting:

/*<collection>*/ sorted /*<order>*/ /*<mode>*/
Try in Playground

Note that both /*<order>*/ and /*<mode>*/ are literal words and cannot be specified dynamically using expressions.

The following table describes the supported orders:

OrderDescription
ascendingSort the elements in ascending order (e.g., from the smallest to the largest). This is the default order.
descendingSort the elements in descending order (e.g., from the largest to the smallest).

And these are the supported modes and the types they support:

ModeSupported typeDescription
alphabeticalStringSort the elements alphabetically.
alphanumericalStringSort the elements alphanumerically, also known as natural sorting. This mode differs from alphabetical because numbers are sorted numerically rather than lexicographically. For example, 10 sorts after 2 in alphabetical mode but before 2 in alphanumerical mode.
numericalNumber or stringSort the elements numerically. This mode differs from alphanumerical in that it supports comparing numeric strings, integers, decimals, and floats — not just numbers.

By default, the modifier uses the ascending order and the natural sorting mode, which follows the same comparison rules as the relational operators.

Parameters

These are the supported parameters:

collection

The collection to sort.

Examples

Here is a basic example of using this modifier with a list:

[3, 1, 2] sorted // [1, 2, 3]
Try in Playground

You can also use this modifier to sort a map:

["a": 3, "b": 1, "c": 2] sorted // ["b": 1, "c": 2, "a": 3]
Try in Playground

To sort a collection in a different order, you can specify the direction:

[1, 3, 2] sorted descending // [3, 2, 1]
Try in Playground

And to sort a collection in a specific way, you can specify the mode:

["a", "10", "2"] sorted numerical // ["2", "10", "a"]
Try in Playground