TypedArray.prototype.toSorted()

The toSorted() method is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order. This method has the same algorithm as Array.prototype.toSorted(), except that it sorts the values numerically instead of as strings by default. TypedArray is one of the typed array types here.

Syntax

// Functionless
toSorted()

// Arrow function
toSorted((a, b) => { /* … */ })

// Compare function
toSorted(compareFn)

// Inline compare function
toSorted(function compareFn(a, b) { /* … */ })

Parameters

compareFn Optional

Specifies a function that defines the sort order.

Return value

A new typed array with the elements sorted in ascending order.

Examples

Sorting an array

For more examples, see also the Array.prototype.sort() method.

const numbers = new Uint8Array([40, 1, 5, 200]);
const numberSorted = numbers.toSorted();
console.log(numberSorted); // Uint8Array [ 1, 5, 40, 200 ]
// Unlike plain Arrays, a compare function is not required
// to sort the numbers numerically.
console.log(numbers); // Uint8Array [ 40, 1, 5, 200 ]

Specifications

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.tosorted

Browser compatibility

BCD tables only load in the browser

See also