JavaScript (ES2026) reference · Array Methods

JavaScript Array toSorted() Method

Return a new sorted array, leaving the original unchanged. Takes the same compare function as sort().

JavaScript (ES2026) Since ES2023

Syntax

array.toSorted(compareFn)

Parameters

ParameterDescription
compareFn optional As in sort().

Return value

A new array.

Examples

Sorted copyTry it yourself
const prices = [30, 5, 12];
console.log(prices.toSorted((a, b) => a - b), prices);

Output

[ 5, 12, 30 ] [ 30, 5, 12 ]
Case-insensitive alphabetical orderTry it yourself
const names = ["bob", "Alice", "carol"];
console.log(names.toSorted((a, b) => a.localeCompare(b)));

Output

[ 'Alice', 'bob', 'carol' ]

Version history

VersionChange
JavaScript ES2023Added

In other languages