The toSorted() method of the Array class in JavaScript returns a new array with the elements sorted in ascending order, without modifying the original array.
There are 2 variations for the syntax of Array.toSorted() method. They are:
toSorted()
This method returns a new array with the elements sorted in ascending, UTF-16 code unit order.
Returns value of type Array
.
toSorted(compareFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
compareFn | optional | A function that defines the sort order. It takes two arguments: a and b. If compareFn(a, b) is less than 0, a comes before b. If compareFn(a, b) is greater than 0, a comes after b. If compareFn(a, b) is equal to 0, the order remains unchanged. |
This method returns a new array with the elements sorted according to the compare function.
Returns value of type Array
.
In JavaScript, we can use the toSorted() method to sort an array of numbers in ascending order without modifying the original array.
For example,
const arr = [5, 3, 8, 1, 2];
const sortedArr = arr.toSorted();
console.log(sortedArr); // Output: [1, 2, 3, 5, 8]
console.log(arr); // Output: [5, 3, 8, 1, 2]
[1, 2, 3, 5, 8] [5, 3, 8, 1, 2]
We can use the toSorted() method to sort an array of strings in alphabetical order without modifying the original array.
For example,
const strArr = ['banana', 'apple', 'cherry', 'date'];
const sortedStrArr = strArr.toSorted();
console.log(sortedStrArr); // Output: ['apple', 'banana', 'cherry', 'date']
console.log(strArr); // Output: ['banana', 'apple', 'cherry', 'date']
['apple', 'banana', 'cherry', 'date'] ['banana', 'apple', 'cherry', 'date']
We can use the toSorted() method with a compare function to sort an array of numbers in descending order without modifying the original array.
For example,
const arr = [5, 3, 8, 1, 2];
const compareNumbers = (a, b) => b - a;
const sortedArr = arr.toSorted(compareNumbers);
console.log(sortedArr); // Output: [8, 5, 3, 2, 1]
console.log(arr); // Output: [5, 3, 8, 1, 2]
[8, 5, 3, 2, 1] [5, 3, 8, 1, 2]
In this JavaScript tutorial, we learned about toSorted() method of Array: the syntax and few working examples with output and detailed explanation for each example.