![]() |
VOOZH | about |
The JS arr.toSorted() method rearranges the array elements alphabetically and returns a new sorted array.
Output
[ 'JS', 'HTML', 'CSS' ]
[ 'CSS', 'HTML', 'JS' ]
Array.toSorted is the immutable version of array.sort() introduced in JavaScript with the ECMAScript 2023 (ES2023) specification. It is not supported in the old versions of ECMAScript.
Syntax: let array = arr.toSorted(compareFunction)Parameters
arr: The array to be sorted.compareFunction (Optional): A function that defines the sort order. If omitted, the array elements are sorted based on their string Unicode code points.Return value: This method returns a new sorted array.
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Output
["JS", "HTML", "CSS"]Convert the string to lowecase in the comparator function.
Output
[ 'css', 'CSS', 'HTML', 'html', 'JS' ]Go through this, JavaScript String Sort, to learn more about sorting string in JS
Array.toSorted() sorts the elements in lexicographical order whether a string or number.
Output
[ 10, 100, 20, 25, 40 ]To sort the numeric array propery we have to pass a comparator function.
Output
[ 10, 20, 25, 40, 100]Change the comparator function to sort the array in descending order.
Output
[ 100, 40, 25, 20, 10 ]We can use the custom comparision function to sort the complex arrays like array of objects.
Output
[
{ name: 'Jatin', age: 25 },
{ name: 'Rahul', age: 28 },
{ name: 'Vikas', age: 32 },
{ name: 'Rohit', age: 35 }
]
[
{ name: 'Jatin', age: 25 },
{ name: 'Rahul', age: 28 },
{ name: 'Rohit', age: 35 },
{ name: 'Vikas', age: 32 }
]