DEV Community

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

Posted on β€’ Edited on

1 1 1 1 1

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 😍

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay