Array.prototype.toSorted()

Returns a new sorted array without mutating the original.

Since ES2023 Spec ↗

Syntax

arr.toSorted(compareFn)

Parameters

NameTypeRequiredDescription
compareFn Function No Comparator (a, b) returning a negative, zero, or positive number. If omitted, elements are compared as strings.

Returns

Array — A new array with elements sorted.

Examples

const a = [3, 1, 2];
console.log(a.toSorted(), a);
Output
[ 1, 2, 3 ] [ 3, 1, 2 ]
console.log([10, 2, 1].toSorted((x, y) => x - y));
Output
[ 1, 2, 10 ]

Notes

The non-mutating version of `sort`. Like `sort`, the default comparison is string-based, so pass a comparator for numbers.

Browser & runtime support

EnvironmentSince version
chrome 110
firefox 115
safari 16
edge 110
node 20

See also