Open In App

JavaScript Array toSorted() Method

The toSorted() method is introduced in JavaScript with the ECMAScript 2023 (ES2023) specification. It provides a safe way to sort an array of elements in ascending order. It will return the new array and the existing array will not be affected.

Sorts elements by converting them to strings by default. Undefined values are positioned at the end of the sorted array.

Syntax:

//With no parameters
let result_array = actual_array.toSorted()

// Ascending Order
let result_array = actual_array.toSorted((a, b) => a - b)

// Descending Order
let result_array = actual_array.toSorted((a, b) => b - a)

Example 1: To demonstrate sorting the array using the toSorted() method in JavaScript without passing any parameter.

let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);

let result_array = actual_array
    .toSorted();
console.log("Final Array: ", result_array);

Output:

Existing Array: [60, 78, 90, 34, 67]
Final Array: [34, 60, 67, 78, 90]

Example 2: Ascending Order - Passing the "compareFn". To demonstrate sorting the array in ascending order using the toSorted() method in JavaScript.

let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);

let result_array = actual_array
    .toSorted((a, b) => a - b);
console.log("Final Array: ", result_array);

Output:

Existing Array: [60, 78, 90, 34, 67]
Final Array: [34, 60, 67, 78, 90]

Example 3: To demonstrate sorting the array in ascending order using the toSorted() method in JavaScript.

let actual_array = [60,78,90,34,67];
console.log("Existing Array: ",actual_array);

let result_array = actual_array.toSorted((a, b) => b - a);
console.log("Final Array: ",result_array);

Output:

Existing Array: [60, 78, 90, 34, 67]
Final Array: [90, 78, 67, 60, 34]
Article Tags :