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]
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]
Browser compatibility
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)