---
title: "array:sort()"
description: "Returns a new array with members sorted using an optional collation and key function."
date: 2026-04-19T00:00:00Z
version: "3.0"
versionLabel: "XSLT 3.0"
category: "array function"
syntax: "array:sort(array, collation?, key-function?)"
tags: ["xslt", "reference", "xpath", "xslt3"]
---
## Description
`array:sort()` returns a new array whose members are in ascending order, determined by the sort key and collation. When no key function is supplied, members are compared directly using the default collation for strings or natural ordering for numbers and other atomic types. When a key function is supplied, it is applied to each member to derive the sort key; members are then sorted by their keys.
This function is the array equivalent of `sort()` for sequences or `xsl:sort` in templates. It does not modify the input array; it always returns a new one.
The `collation` argument controls string comparison. The `key-function` takes a single argument (the array member, which is a sequence) and returns an atomic value to use as the sort key.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `array` | array(*) | Yes | The input array to sort. |
| `collation` | xs:string? | No | URI of the collation to use for string comparison. Empty sequence uses the default. |
| `key-function` | function(item()*) as xs:anyAtomicType* | No | A function that extracts the sort key from each member. |
## Return value
`array(*)` — a new array with the same members in sorted order.
## Examples
### Sorting numbers in ascending order
**Stylesheet:**
```xml
```
**Output:**
```
1 2 3 5 8 9
```
### Sorting records by a key field
**Input XML:**
```xml
```
**Stylesheet:**
```xml
```
**Output:**
```xml
```
## Notes
- `array:sort()` always sorts in ascending order. To sort in descending order, reverse the result with `array:reverse()`.
- The collation argument may be `()` (empty sequence) to use the default collation, allowing the key function to be specified without supplying a collation.
- Members that are sequences are compared by their atomized value; members that cannot be compared raise a type error.
- An empty array returns an empty array.
## See also
- [array:filter()](../xpath-array-filter)
- [array:for-each()](../xpath-array-for-each)
- [array:reverse()](../xpath-array-reverse)
- [sort()](../xpath-sort)