JavaScript Array toSorted() Method: Creating a Sorted Array
The toSorted() method in JavaScript is a powerful tool for creating a new sorted array from an existing one, without modifying the original array. Unlike the sort() method, which sorts the array in place, toSorted() ensures immutability, making it ideal for functional programming and avoiding unintended side effects. This comprehensive guide will explore the syntax, usage, and practical applications of the toSorted() method.
What is the toSorted() Method?
The toSorted() method is an ECMAScript 2023 feature that allows you to sort an array and return a new, sorted array while leaving the original array unchanged. This method is particularly useful when you need to maintain the original array’s order or when working with libraries that rely on immutability.
Purpose of toSorted()
The primary purpose of the toSorted() method is to provide a non-mutating way to sort arrays. This is beneficial in several situations:
- Immutability: Preserves the original array, preventing accidental modifications.
- Functional Programming: Supports functional programming paradigms where data should be immutable.
- Predictable Behavior: Ensures the state of the original array is always consistent.
- Avoiding Side Effects: Reduces the chance of introducing bugs due to unexpected changes in data.
Syntax of the toSorted() Method
The toSorted() method has a simple and straightforward syntax:
array.toSorted(compareFunction);
Parameters
| Parameter | Type | Description |
|---|---|---|
| `compareFunction` (optional) | Function |
A function that defines the sort order. It takes two arguments (a and b) and should return:
|
compareFunction(Optional): If omitted, the array elements are converted to strings and sorted lexicographically. For numbers or custom objects, it is essential to provide a customcompareFunctionto ensure correct sorting.
Return Value
- A new sorted array, leaving the original array unchanged.
Examples of toSorted() in Action
Let’s explore some practical examples of how to use the toSorted() method to sort arrays effectively.
Basic Sorting of Numbers
When sorting numbers, the default lexicographical sort does not work correctly. You must provide a comparison function.
const numbers_1 = [3, 1, 4, 1, 5, 9, 2, 6];
const sortedNumbers_1 = numbers_1.toSorted((a, b) => a - b);
console.log("Original Array:", numbers_1);
console.log("Sorted Array:", sortedNumbers_1);
Output:
Original Array: [3, 1, 4, 1, 5, 9, 2, 6]
Sorted Array: [1, 1, 2, 3, 4, 5, 6, 9]
Sorting Strings Alphabetically
By default, the toSorted() method sorts strings alphabetically if no compare function is provided.
const names_1 = ["Charlie", "Alice", "Bob", "David"];
const sortedNames_1 = names_1.toSorted();
console.log("Original Array:", names_1);
console.log("Sorted Array:", sortedNames_1);
Output:
Original Array: ['Charlie', 'Alice', 'Bob', 'David']
Sorted Array: ['Alice', 'Bob', 'Charlie', 'David']
Sorting in Reverse Order
To sort in reverse order, use a compareFunction that reverses the usual comparison.
const numbers_2 = [3, 1, 4, 1, 5, 9, 2, 6];
const sortedNumbers_2 = numbers_2.toSorted((a, b) => b - a);
console.log("Original Array:", numbers_2);
console.log("Sorted Array:", sortedNumbers_2);
Output:
Original Array: [3, 1, 4, 1, 5, 9, 2, 6]
Sorted Array: [9, 6, 5, 4, 3, 2, 1, 1]
Sorting Objects by a Specific Property
You can sort arrays of objects by a specific property using a custom comparison function.
const products_1 = [
{ name: "Laptop", price: 1200 },
{ name: "Tablet", price: 300 },
{ name: "Phone", price: 800 },
];
const sortedProducts_1 = products_1.toSorted((a, b) => a.price - b.price);
console.log("Original Array:", products_1);
console.log("Sorted Array:", sortedProducts_1);
Output:
Original Array: [
{ name: 'Laptop', price: 1200 },
{ name: 'Tablet', price: 300 },
{ name: 'Phone', price: 800 }
]
Sorted Array: [
{ name: 'Tablet', price: 300 },
{ name: 'Phone', price: 800 },
{ name: 'Laptop', price: 1200 }
]
Sorting with Case-Insensitive String Comparisons
For case-insensitive sorting of strings, use toLowerCase() or toUpperCase() in the comparison function.
const names_2 = ["apple", "Banana", "cherry", "Date"];
const sortedNames_2 = names_2.toSorted((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase())
);
console.log("Original Array:", names_2);
console.log("Sorted Array:", sortedNames_2);
Output:
Original Array: ['apple', 'Banana', 'cherry', 'Date']
Sorted Array: ['apple', 'Banana', 'cherry', 'Date']
Sorting with Complex Criteria
You can combine multiple properties to create more complex sorting criteria.
const employees_1 = [
{ name: "Alice", department: "HR", salary: 60000 },
{ name: "Bob", department: "IT", salary: 70000 },
{ name: "Charlie", department: "HR", salary: 50000 },
{ name: "David", department: "IT", salary: 70000 },
];
const sortedEmployees_1 = employees_1.toSorted((a, b) => {
if (a.department < b.department) return -1;
if (a.department > b.department) return 1;
return b.salary - a.salary;
});
console.log("Original Array:", employees_1);
console.log("Sorted Array:", sortedEmployees_1);
Output:
Original Array: [
{ name: 'Alice', department: 'HR', salary: 60000 },
{ name: 'Bob', department: 'IT', salary: 70000 },
{ name: 'Charlie', department: 'HR', salary: 50000 },
{ name: 'David', department: 'IT', salary: 70000 }
]
Sorted Array: [
{ name: 'Charlie', department: 'HR', salary: 50000 },
{ name: 'Alice', department: 'HR', salary: 60000 },
{ name: 'David', department: 'IT', salary: 70000 },
{ name: 'Bob', department: 'IT', salary: 70000 }
]
In this example, employees are first sorted by department, and within the same department, they are sorted by salary in descending order.
Key Differences from sort()
The key distinction between toSorted() and sort() is that toSorted() creates a new array, leaving the original untouched, while sort() modifies the original array in place.
| Feature | `toSorted()` | `sort()` |
|---|---|---|
| Mutation | Creates a new sorted array, the original array is unchanged. | Sorts the array in place, modifies the original array. |
| Immutability | Immutability is maintained. | Original array mutated which may cause unintended side effects. |
| Use Cases | Ideal for functional programming and situations requiring immutability. | Suitable when modifying the original array is acceptable. |
Choose toSorted() when you need to preserve the original array, and sort() when you’re okay with in-place modifications. 🤔
Practical Use Cases
The toSorted() method is particularly beneficial in scenarios where maintaining immutability is important:
-
React State Management: In React applications, it’s crucial to avoid directly modifying state. Using
toSorted()ensures that state updates trigger re-renders correctly. -
Redux and Other State Libraries: When working with state management libraries like Redux, using immutable operations like
toSorted()helps in predictable state changes. -
Functional Programming: In functional programming paradigms, it’s vital to have operations that don’t modify existing data.
toSorted()supports this by returning a new, sorted array. -
Data Processing Pipelines: When working with data transformations,
toSorted()can help build a pipeline of operations that do not change the original input data. -
Immutable Data Structures: In situations where immutability is required,
toSorted()is a natural fit.
Browser Support
The toSorted() method is a recent addition to JavaScript and enjoys wide support in modern browsers.
| Browser | Support |
| ————– | ——- |
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Opera | Yes |
| Mobile Chrome | Yes |
| Mobile Safari | Yes |
| Android Browser| Yes |
Conclusion
The toSorted() method is a valuable addition to the JavaScript array manipulation arsenal. Its ability to create sorted arrays without modifying the original array makes it ideal for modern web development practices, particularly where immutability and predictability are crucial. By understanding its syntax, usage, and advantages over the in-place sort() method, you can effectively leverage toSorted() in your projects. 🎉







