The JavaScript Array.toSorted() method creates a new array with the elements sorted in ascending order. Unlike the Array.sort() method, which modifies the original array, toSorted() returns a sorted copy, leaving the original array unchanged. This makes it useful in scenarios where immutability is important.
For example, array.toSorted() is helpful when you need a sorted version of an array while preserving the original order of elements in the array.
Syntax
The syntax for the Array.toSorted() method is:
array.toSorted([compareFunction])
Parameters
The Array.toSorted() method accepts one optional parameter:
- compareFunction (Optional): A function that defines the sort order. It takes two arguments:
- firstElement: The first element to compare.
- secondElement: The second element to compare. If the function returns:
- A negative value, firstElement comes before secondElement. A positive value, firstElement comes after secondElement. 0, both elements are treated as equal.
Return Value
A new array with the elements sorted as specified by the compare function or in lexicographical order if no compare function is provided.
Examples of JavaScript Array.toSorted() Method
Example 1: Sorting Numbers Without Modifying the Original Array
You can use the toSorted() method to sort numbers without modifying the original array.
const numbers = [10, 1, 21, 2];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // Output: [1, 10, 2, 21]
console.log(numbers); // Output: [10, 1, 21, 2]
Explanation: The toSorted() method creates a new array where the numbers are sorted in lexicographical order by default, but the original numbers array remains unchanged.
Example 2: Sorting Numbers in Ascending Order
To sort numbers in ascending numerical order, you need to provide a custom compare function.
const numbers = [10, 1, 21, 2];
const sortedNumbers = numbers.toSorted((a, b) => a - b);
console.log(sortedNumbers); // Output: [1, 2, 10, 21]
Explanation: The compare function (a, b) => a - b ensures the numbers are sorted in ascending numerical order, and a new sorted array is returned.
Example 3: Sorting Strings Alphabetically
You can use toSorted() to sort an array of strings in alphabetical order.
const fruits = ['banana', 'apple', 'mango'];
const sortedFruits = fruits.toSorted();
console.log(sortedFruits); // Output: ['apple', 'banana', 'mango']
Explanation: The toSorted() method sorts the strings alphabetically and returns a new array, leaving the original fruits array unchanged.
Example 4: Sorting Strings in Reverse Alphabetical Order
You can provide a custom compare function to sort strings in reverse alphabetical order.
const fruits = ['banana', 'apple', 'mango'];
const sortedFruits = fruits.toSorted((a, b) => b.localeCompare(a));
console.log(sortedFruits); // Output: ['mango', 'banana', 'apple']
Explanation: The localeCompare() method is used in the compare function to sort the strings in reverse alphabetical order.
Example 5: Sorting an Array of Objects by Property
You can use the toSorted() method to sort an array of objects based on a specific property.
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
const sortedUsers = users.toSorted((a, b) => a.age - b.age);
console.log(sortedUsers);
// Output: [{ name: 'Charlie', age: 20 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }]
Explanation: The compare function sorts the users array by the age property in ascending order, creating a new sorted array without modifying the original one.
Example 6: Sorting Strings with Different Locales
You can sort strings in a locale-aware manner by using localeCompare() in the compare function.
const words = ['Éclair', 'Apple', 'Zebra'];
const sortedWords = words.toSorted(
(a, b) => a.localeCompare(b, 'fr', { sensitivity: 'base' }));
console.log(sortedWords); // Output: ['Apple', 'Éclair', 'Zebra']
Explanation: The localeCompare() method sorts the strings based on French locale rules, resulting in a new array that considers locale-specific alphabetical order.