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
| Name | Type | Description |
|---|---|---|
| compareFn | Function | Defines 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().