JavaScript Array.toSorted() method (with examples)

Updated: September 8, 2023 By: Khue Post a comment

This concise, practical article is about the Array.toSorted() method in modern JavaScript.

Overview

The Array.toSorted() method is a new feature in JavaScript (since ECMAScript 2023 or ES14) that allows you to sort an array without changing the original array. It returns a new array with the elements sorted in ascending order by default, or according to a custom function that you can provide as an argument.

This method is useful when you want to keep the original order of the array intact, or when you want to sort different copies of the same array in different ways. It’s supported by most modern web browsers, like Chrome, Edge, Safari, Firefox, on both desktop and mobile.

Syntax:

array.toSorted([compareFn])

Here, the optional parameter compareFn, is a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value. If provided,compareFn should take two parameters (a and b) and return a negative number if a should come before b, a positive number if a should come after b, or zero if they are equal.

The return value is a new array. This makes the Array.toSorted() method different from the Array.sort() method, which sorts the elements of an array in place and returns the same array reference.

Examples

I personally think learning by example is one of the best approaches to get good in programming, especially in JavaScript.

Sorting an array of strings

This example shows you how to use the Array.toSorted() method to sort an array of strings in alphabetical order.

// an array of strings
const originalArray = ['Dog', 'Cat', 'Turtle', 'Wolf', 'Sling Academy']

// use the toSorted() method to sort the array
const sortedArray = originalArray.toSorted();

// log the original array
console.log(originalArray); 
// ['Dog', 'Cat', 'Turtle', 'Wolf', 'Sling Academy']

// log the sorted array
console.log(sortedArray); 
// ['Cat', 'Dog', 'Sling Academy', 'Turtle', 'Wolf']

Sorting an array of numbers

This example demonstrates the way to use the Array.toSorted() method to sort an array of numbers in ascending order and in descending order.

numbers = [3, 2, 4, 1, 5, 10, 6, 7, 9, 8];

// sort numbers in ascending order
ascNumbers = numbers.toSorted((a, b) => a - b);
console.log(ascNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// sort numbers in descending order
descNumbers = numbers.toSorted((a, b) => b - a);
console.log(descNumbers); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Sorting an array of objects by property value

he Array.toSorted() method can be used to sort an array of objects by providing a compare function that accesses a property value of each object and compares them. Let’s say we have an array of products where each product has a name and a price. A compare function that compares the price property of two objects can be used to sort them by price (from low to high or from high to low).

// array of products
const products = [
    { name: 'Blue T-shirt', price: 79 },
    { name: 'Black Shoes', price: 99.99, },
    { name: 'Pink Hat', price: 29.50, },
    { name: 'Red Pants', price: 89.99, }
];

// Sort by price : lowest to highest
lowToHigh = products.toSorted((a, b) => a.price - b.price);
console.log(lowToHigh);
/* Output
[
    { name: 'Pink Hat', price: 29.5 },
    { name: 'Blue T-shirt', price: 79 },
    { name: 'Red Pants', price: 89.99 },
    { name: 'Black Shoes', price: 99.99 }
]
*/

// Sort by price : highest to lowest
highToLow = products.toSorted((a, b) => b.price - a.price);
console.log(highToLow);
/* Output
[
    { name: 'Black Shoes', price: 99.99 },
    { name: 'Red Pants', price: 89.99 },
    { name: 'Blue T-shirt', price: 79 },
    { name: 'Pink Hat', price: 29.5 }
]
*/

Final Words

The Array.toSorted() method is a useful addition to JavaScript, as it allows developers to sort arrays without modifying the original ones. This can help prevent unwanted side effects and improve code readability and maintainability. Moreover, the Array.toSorted() method is consistent with the functional programming paradigm, which favors immutable data structures and pure functions. The trade-off is that the method may not be compatible with older browsers or environments that do not support ECMAScript 2023, so you may need to use polyfills or transpilers to ensure compatibility.