array:sort

Returns an array containing all the members of the supplied array, sorted according to the value of a sort key supplied as a function.

Signatures

array:sort($array as array(*)) as array(*)
array:sort(
    $array as array(*), 
    $collation as xs:string?
) as array(*)
array:sort(
    $array as array(*), 
    $collation as xs:string?, 
    $key as function(item()*) as xs:anyAtomicType*
) as array(*)

Properties

The one-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations.

The two-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations.

The two-argument form of this function is deterministic, context-independent, focus-independent, and higher-order.

Rules

Calling the single-argument version of the function is equivalent to calling the two-argument form with default-collation() as the second argument: that is, it sorts the members of an array according to the typed value of the items, using the default collation to compare strings.

Calling the two-argument version of the function is equivalent to calling the three-argument form with fn:data#1 as the third argument: that is, it sorts the members of an array according to the typed value of the items, using a specified collation to compare strings.

In the case of both array:sort#2 and array:sort#3, supplying an empty sequence as the second argument is equivalent to supplying fn:default-collation(). For more information on collations see Choosing a collation.

The result of the function is obtained as follows:

Error Conditions

If the set of computed sort keys contains values that are not comparable using the le operator then the sort operation will fail with a dynamic error.

Examples

The expression array:sort([1, 4, 6, 5, 3]) returns [1, 3, 4, 5, 6].

The expression array:sort([1, -2, 5, 10, -10, 10, 8], (), fn:abs#1) returns [1, -2, 5, 8, 10, -10, 10].

The expression array:sort([(1,0), (1,1), (0,1), (0,0)]) returns [(0,0), (0,1), (1,0), (1,1)].

To sort an array of strings $in using Swedish collation:

let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se"
return array:sort($in, $SWEDISH)
            

To sort an array of maps representing employees, using last name as the major sort key and first name as the minor sort key, with the default collation:

array:sort($employees, (), function($emp) {$emp?name?last, $emp?name?first})