typedArray.toSorted() is the copying version of sort(). It returns a new typed array of the same type with the elements in numeric order, and the original stays as it is. Like sort(), it can take a comparator function. It was added in ES2023, together with toReversed() and with(). The new array has its own ArrayBuffer.
Remember
typedArray.toSorted() → NEW typed array, numeric order
typedArray.toSorted(compareFn) → your order
const a = new Uint8Array([10, 9, 1]);
a.toSorted() // 1 9 10
a // still 10 9 1
sort() → changes the original
toSorted() → leaves it alone
Syntax
The comparator is optional. Without it, the copy is sorted from smallest to largest.
Get a copy from the largest value to the smallest.
ta.toSorted().at(-1)
Read the biggest value without sorting the original.
Added in ES2023 for all 11 typed array types. Older browsers do not have it; use ta.slice().sort() there.
Library declarations
JavaScript
TypedArray.prototype.toSorted(compareFn) // returns a new typed array
// same type and length as the original, new ArrayBuffer
// the original typed array is not modified
Parameters
Parameter
Description
compareFn (optional)
A function (a, b) that returns a negative number, a positive number, or 0, just like for sort(). Anything else (not a function and not undefined) throws a TypeError.
Return Value
Return Value
Description
TypedArray
A new sorted typed array of the same type and length. It does not share memory with the original.
JavaScript Examples
Example 1 — Sort Without Touching the Original
Delivery times in minutes are stored in a Uint8Array. We want them in order, but the original arrival order must stay.