Array.toSorted()
The Array.toSorted()
method in JavaScript returns a new array with the elements sorted in ascending order by default, or sorted according to the provided comparison function. This method does not modify the original array.
Syntax
toSorted()
toSorted(compareFn)
Parameters
Parameter | Description |
---|---|
compareFn (optional) | A function that defines the sort order. It takes two arguments, a and b , and returns:
|
Return Value
The toSorted()
method returns a new array with the elements sorted according to the specified criteria. The original array remains unchanged.
Examples
1. Sorting an Array of Numbers in Ascending Order
By default, toSorted()
sorts numbers in ascending order as strings.
const numbers = [5, 1, 3, 2, 4];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers);
Output
[1, 2, 3, 4, 5]
- The
toSorted()
method creates a new array sorted in ascending order. - The original array
numbers
remains unchanged.
2. Sorting with a Custom Comparison Function
Using a comparison function, you can define custom sorting behavior, such as sorting numbers in descending order.
const numbers = [5, 1, 3, 2, 4];
const sortedDescending = numbers.toSorted((a, b) => b - a);
console.log(sortedDescending);
Output
[5, 4, 3, 2, 1]
- The comparison function
(a, b) => b - a
sorts numbers in descending order. - The original array
numbers
is unaffected by the sorting operation.
3. Sorting an Array of Strings
The toSorted()
method can also sort strings in lexicographical order by default.
const fruits = ['banana', 'apple', 'cherry', 'date'];
const sortedFruits = fruits.toSorted();
console.log(sortedFruits);
Output
['apple', 'banana', 'cherry', 'date']
Strings are sorted in lexicographical order by default.
4. Sorting with Mixed Data Types
The toSorted()
method can be used with mixed data types, but a custom comparison function is necessary for predictable results.
const mixed = [10, '20', 3, 'apple'];
const sortedMixed = mixed.toSorted((a, b) => a.toString().localeCompare(b.toString()));
console.log(sortedMixed);
Output
[ 10, '20', 3, 'apple' ]
A custom comparison function can handle mixed types for consistent sorting behavior.