VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-array-tosorted-method/

⇱ JavaScript Array toSorted() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Array toSorted() Method

Last Updated : 23 Jul, 2025

The JS arr.toSorted() method rearranges the array elements alphabetically and returns a new sorted array.

Sorting Array of Strings

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.

In Reverse Order

Output

["JS", "HTML", "CSS"]

Case Insensitive Sorting of Strings

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

Sorting a Numeric Array in JS

Ascending Order

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]

Descending Order

Change the comparator function to sort the array in descending order.

Output

[ 100, 40, 25, 20, 10 ]

Sorting Complex Arrays

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 }
]
Comment