Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.toSorted

Returns a sorted copy of an array without changing the original.

Available since: ES2023

Syntax

array.toSorted(compareFn)

Parameters

ParameterTypeDescription
compareFnFunctionOptional. A function that compares two elements and returns a negative number, zero or a positive number.

Return value

ArrayA new sorted array.

Examples

The original array stays the same:

const prices = [30, 5, 120];
const sorted = prices.toSorted((a, b) => a - b);
 
console.log(sorted.join(', '));
console.log(prices.join(', '));

Output:

5, 30, 120
30, 5, 120

Sorting objects by name:

const users = [{ name: 'Oleg' }, { name: 'Anna' }];
 
console.log(users.toSorted((a, b) => a.name.localeCompare(b.name)).map((u) => u.name).join(', '));

Output:

Anna, Oleg

Notes

Without a compare function elements are compared as strings, so [10, 9].toSorted() gives [10, 9]. For numbers always pass (a, b) => a - b.

See also

Related recipes

In the tutorial

  • Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.

Thanks for reading!

Donate to the site — we work hard for you.