DEV Community

Cover image for JavaScript - Array toSorted() Method
Kristiyan Velkov
Kristiyan Velkov

Posted on • Edited on

JavaScript - Array toSorted() Method

What it is?

The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

NB!: Sort() method modifies the original array.

Example of use:

Here’s an example to illustrate the difference between toSorted and sort:

const numbers = [3, 4, 1, 5, 2];
const sortedNumbers = numbers.toSorted();

console.log(numbers); // Output: [3, 4, 1, 5, 2]
console.log(sortedNumbers); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

The sort method, on the other hand, modifies the original array in place. Here's an example:

const numbers = [3, 4, 1, 5, 2];
numbers.sort();

console.log(numbers); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Browser compatibility

Image description


Image description

linkedin


Image description

If you like my work and want to support me to work hard, please donate via:

Revolut website payment or use the QR code above.

Thanks a bunch for supporting me! It means a LOT 😍

Top comments (0)