JavaScript Array toSorted() Method
Last Updated :
15 Nov, 2024
The JS arr.toSorted() method rearranges the array elements alphabetically and returns a new sorted array.
Sorting Array of Strings
JavaScript
const arr = ["JS", "HTML", "CSS"];
const arr1 = arr.toSorted();
console.log(arr);
console.log(arr1);
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
JavaScript
// Original array
let arr = ["HTML", "JS", "CSS"];
// Sort in reverse order using toSorted()
let arr1 = arr.toSorted((a, b) => b.localeCompare(a));
console.log(arr1); // Sorted in reverse order
Output
["JS", "HTML", "CSS"]
Case Insensitive Sorting of Strings
Convert the string to lowecase in the comparator function.
JavaScript
let arr = ["HTML", "html", "css", "CSS", "JS"];
// convert strings to lowercase
let arr1 = arr.toSorted((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(arr1);
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.
JavaScript
const arr = [ 10, 20, 25, 100 , 40]
console.log(arr.toSorted())
Output
[ 10, 100, 20, 25, 40 ]
To sort the numeric array propery we have to pass a comparator function.
JavaScript
const arr = [10, 20, 25, 100, 40];
// Modify comparision function
const arr1 = arr.toSorted((a, b) => a - b);
console.log(arr1);
Output
[ 10, 20, 25, 40, 100]
Descending Order
Change the comparator function to sort the array in descending order.
JavaScript
const arr = [10, 20, 25, 100, 40];
// Modify comparision function
const arr1 = arr.toSorted((a, b) => b - a);
console.log(arr1);
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.
JavaScript
// Array of people objects with different names and ages
let arr = [
{ name: 'Rahul', age: 28 },
{ name: 'Jatin', age: 25 },
{ name: 'Vikas', age: 32 },
{ name: 'Rohit', age: 35 }
];
// Custom comparison function for sorting by age
let sortedByAge = arr.toSorted((a, b) => a.age - b.age);
console.log(sortedByAge);
// Custom comparison function for sorting objects by name
let sortedByName = arr.toSorted((a, b) => a.name.localeCompare(b.name));
// Sorted by name
console.log(sortedByName);
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 }
]
Similar Reads
JavaScript Array sort() Method The JS array.sort() method rearranges the array elements alphabetically and returns a sorted array. It does not create a new array but updates the original array.Sorting Array of StringsJavaScript// Original array let ar = ["JS", "HTML", "CSS"]; console.log(ar); // Sorting the array ar.sort() consol
4 min read
JavaScript Sort() Method JS sort() method is used to rearrange the array elements alphabetically in ascending order. It updates the given array and does not return anything.JavaScriptlet arr = ["HTML", "CSS", "JS"]; arr.sort(); console.log(arr);Output[ 'CSS', 'HTML', 'JS' ] Sorting Array of Strings in Descending OrderModify
3 min read
JavaScript TypedArray.prototype.toSorted() Method The toSorted() method, presented in ECMAScript 2023 or (ES2023) affords a secure and efficient manner of ordering elements of TypedArray in ascending order. The toSorted() method of TypedArray instances is the copying version of the sort() method, it gives back a new typed array with sorted elements
1 min read
How toSorted() method is different from sort() in JavaScript In JavaScript, sort() and toSorted() methods do the same job as sorting but toSorted() does not change the original array. sort() method changes the original array. Below we have explained both the methods. Table of Content Sort() MethodtoSorted() MethodSort() Method:The sort() method is a built-in
2 min read
Javascript Program to Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
How to sort an Array in C# | Array.Sort() Method Set â 2 Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method
9 min read
ArrayList toArray() method in Java with Examples The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.Declaring toArray() methodpublic Object[] toArray() or public <T> T[] toArray(T[] a)Parameters: This method either accepts no parameters or it takes an array T[] as a para
3 min read
CopyOnWriteArrayList toArray() method in Java The toArray() method of CopyOnWriteArrayList is used to return an array containing all the elements in CopyOnWriteArrayList in the correct order. Syntax: public Object[] toArray() or public <T> T[] toArray(T[] a) Parameters: This method either accepts no parameters or it takes an array T[] a a
2 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
JavaScript Program to find the Nth smallest/largest element from an unsorted Array In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It rep
4 min read