The Array.toSorted()
method is a new addition to JavaScript, introduced in ECMAScript 2023 (ES14). It returns a new array with the elements sorted in the specified order, leaving the original array unchanged.
Syntax
let newArray = arr.toSorted(compareFunction);
Parameters
Parameter | Description |
---|---|
compareFunction | (Optional) A function that defines the sort order. If omitted, elements are converted to strings and sorted lexicographically in ascending order. |
Return Value
The toSorted()
method returns a new array with elements sorted as per the specified order in the compareFunction
.
Example 1: Default Lexicographic Sorting
let arr = ['HTML', 'CSS', 'JavaScript', 'jQuery']; let sortedArr = arr.toSorted(); console.log(sortedArr); // Output: [ 'CSS', 'HTML', 'JavaScript', 'jQuery' ] console.log(arr); // Output: [ 'HTML', 'CSS', 'JavaScript', 'jQuery' ]
By default, toSorted()
arranges elements lexicographically without modifying the original array.
Example 2: Sorting Numbers
let arr = [10, 1, 25, 3]; let sortedArr = arr.toSorted((a, b) => a - b); console.log(sortedArr); // Output: [1, 3, 10, 25] console.log(arr); // Output: [10, 1, 25, 3]
Using a custom compareFunction
, the numbers are sorted in ascending order.
Example 3: Sorting in Descending Order
let arr = [10, 1, 25, 3]; let sortDescending = arr.toSorted((a, b) => b - a); console.log(sortDescending); // Output: [25, 10, 3, 1] console.log(arr); // Output: [10, 1, 25, 3]
The compareFunction
is customized to sort numbers in descending order.
Example 4: Sorting an Array of Objects
let users = [ { name: 'John', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Bob', age: 20 } ]; let sortedByAge = users.toSorted((a, b) => a.age - b.age); console.log(sortedByAge); /* Output: [ { name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Alice', age: 30 } ] */ console.log(users); // Output: Original array remains unchanged
Supported Browsers
Browser | Support |
---|---|
Chrome | 110+ |
Firefox | 109+ |
Safari | 16.4+ |
Edge | 110+ |
Opera | 96+ |
Internet Explorer | Not Supported |