Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
Reference / JavaScript

Array.prototype.toSorted()

Copies an array and returns a new sorted array without mutating the original array (ECMAScript 2023).

Syntax
toSorted(compareFn?: (a: T, b: T) => number): T[]

Parameters

NameTypeDescription
compareFnFunctionDefines the sort order.

Examples

Immutable numerical sorting
const nums = [5, 2, 9, 1];
const sorted = nums.toSorted((a, b) => a - b);
console.log(sorted); // [1, 2, 5, 9]
console.log(nums);   // [5, 2, 9, 1] (Unmutated)
Provides safe immutability compared to Array.prototype.sort().