Version: v0.8.1 - Beta.  We welcome contributors & feedback.

List.sort

sort($functionOrOptions={}) -> self

Description

Sort the order of items by their value.

By default, the sorting is in natural order.

$items = ['d', 'a', 'c', 'e', 'b']

$items.sort()
//= ['a', 'b', 'c', 'd', 'e']

Options

If $functionOrOptions is a map, it can include the following options.

Option Value Description
reverse true/false Sort in descending order.
ignoreCase true/false Case-insensitive sort.
ascii true/false Sort by each character’s ASCII code, instead of natural order.
$items = ['d', 'a', 'c', 'e', 'b']
$items.sort(-reverse)
//= ['e', 'd', 'c', 'b', 'a']

$items = ['d', 'A', 'c', 'E', 'b']
$items.sort({ reverse, ignoreCase })
//= ['E', 'd', 'c', 'b', 'A']

Sort Functions

If $functionOrOptions is a function, it will be called with 2 arguments, each containing a list item that will be compared to the other.

The function should return a numeric comparison (usually with the <=> operator) of the items to create custom sort behavior. (-1 = before, 0 = equal, 1 = after)

See Functional Programming.

$items = [3, 1, -2, 5, -4]

$items.sort(fun ($a, $b) {
    return $a.absolute() <=> $b.absolute()
})
//= [1, -2, 3, -4, 5]

// With expression function x{...}
$items.sort(x{ $a.absolute() <=> $b.absolute() })
//= [1, -2, 3, -4, 5]

// To reverse order, swap the arguments
$items.sort(x{ $b.absolute() <=> $a.absolute() })
                ^                 ^
//= [5, -4, 3, -2, 1]

See Also