Array.toSorted()

The Array.toSorted() method in JavaScript returns a new array with the elements sorted in ascending order by default, or sorted according to the provided comparison function. This method does not modify the original array.

Syntax

</>
Copy
toSorted()
toSorted(compareFn)

Parameters

ParameterDescription
compareFn (optional)A function that defines the sort order. It takes two arguments, a and b, and returns:
  • A negative value if a should come before b.
  • Zero if a and b are equal.
  • A positive value if a should come after b.

Return Value

The toSorted() method returns a new array with the elements sorted according to the specified criteria. The original array remains unchanged.


Examples

1. Sorting an Array of Numbers in Ascending Order

By default, toSorted() sorts numbers in ascending order as strings.

</>
Copy
const numbers = [5, 1, 3, 2, 4];

const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers);

Output

[1, 2, 3, 4, 5]
  1. The toSorted() method creates a new array sorted in ascending order.
  2. The original array numbers remains unchanged.

2. Sorting with a Custom Comparison Function

Using a comparison function, you can define custom sorting behavior, such as sorting numbers in descending order.

</>
Copy
const numbers = [5, 1, 3, 2, 4];

const sortedDescending = numbers.toSorted((a, b) => b - a);
console.log(sortedDescending);

Output

[5, 4, 3, 2, 1]
  1. The comparison function (a, b) => b - a sorts numbers in descending order.
  2. The original array numbers is unaffected by the sorting operation.

3. Sorting an Array of Strings

The toSorted() method can also sort strings in lexicographical order by default.

</>
Copy
const fruits = ['banana', 'apple', 'cherry', 'date'];

const sortedFruits = fruits.toSorted();
console.log(sortedFruits);

Output

['apple', 'banana', 'cherry', 'date']

Strings are sorted in lexicographical order by default.

4. Sorting with Mixed Data Types

The toSorted() method can be used with mixed data types, but a custom comparison function is necessary for predictable results.

</>
Copy
const mixed = [10, '20', 3, 'apple'];

const sortedMixed = mixed.toSorted((a, b) => a.toString().localeCompare(b.toString()));
console.log(sortedMixed);

Output

[ 10, '20', 3, 'apple' ]

A custom comparison function can handle mixed types for consistent sorting behavior.