---
layout: default
---
Function sort #
Sort the items in a matrix.
Syntax #
```js
math.sort(x)
math.sort(x, compare)
```
Parameters #
Parameter | Type | Description
--------- | ---- | -----------
`x` | Matrix | Array | A one dimensional matrix or array to sort
`compare` | Function | 'asc' | 'desc' | 'natural' | An optional _comparator function or name. The function is called as `compare(a, b)`, and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'.
Returns #
Type | Description
---- | -----------
Matrix | Array | Returns the sorted matrix.
Throws #
Type | Description
---- | -----------
Examples #
```js
math.sort([5, 10, 1]) // returns [1, 5, 10]
math.sort(['C', 'B', 'A', 'D'], math.compareNatural)
// returns ['A', 'B', 'C', 'D']
function sortByLength (a, b) {
return a.length - b.length
}
math.sort(['Langdon', 'Tom', 'Sara'], sortByLength)
// returns ['Tom', 'Sara', 'Langdon']
```
See also #
[filter](filter.html),
[forEach](forEach.html),
[map](map.html),
[compare](compare.html),
[compareNatural](compareNatural.html)