Horje
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.

JavaScript
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.

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.

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]



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Array toReversed() Method JavaScript Array toReversed() Method
What is the Infinity Global Property in JavaScript ? What is the Infinity Global Property in JavaScript ?
JavaScript Array with() Method JavaScript Array with() Method
How to Filter an Array in JavaScript ? How to Filter an Array in JavaScript ?
JavaScript Program for nth Term of Geometric Progression JavaScript Program for nth Term of Geometric Progression

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13