JavaScript offers two powerful methods for sorting arrays: toSorted() and sort(). While both achieve the same goal of ordering elements, they differ in a crucial way: whether they modify the original array or create a new one. Understanding this distinction is essential for writing clean and efficient code.
toSorted(): The Non-Mutating Newcomer
- Preserves the Original: Creates a separate sorted array, leaving the original intact.
- Syntax: const sortedArray = originalArray.toSorted();
- Default Sorting: Alphabetical (strings).
- Custom Sorting: Accepts a compare function for tailored sorting logic.
- TypedArrays: Has a dedicated toSorted() method for numerical sorting.
sort(): The Classic In-Place Sort
- Modifies the Original: Arranges elements within the same array.
- Syntax: originalArray.sort();
- Default Sorting: Also alphabetical (strings).
- Custom Sorting: Likewise accepts a compare function.
- Broader Compatibility: Supported in older JavaScript environments.
When to Choose Which:
Use toSorted() when:
- You need to preserve the original array for later use.
- You're working with TypedArrays and want numerical sorting by default.
- Memory efficiency isn't a critical concern.
Use sort() when:
- Modifying the original array is acceptable.
- Memory optimization is a priority.
- You're working in older environments where toSorted() might not be available.
Code Examples:
1. Sorting with toSorted()
const numbers = [3, 1, 5, 2];
// Create a new sorted array (original remains unchanged):
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // Output: [1, 2, 3, 5]
console.log(numbers); // Original array remains [3, 1, 5, 2]
// Custom sorting with `toSorted()`:
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
];
const sortedUsers = users.toSorted((a, b) => a.age - b.age);
console.log(sortedUsers); // Output: [{ name: "Charlie", age: 20 }, { name: "Alice", age: 25 }, { name: "Bob", age: 30 }]
2. Sorting with sort()
const fruits = ["banana", "apple", "orange"];
// Modify the original array:
fruits.sort();
console.log(fruits); // Output: ["apple", "banana", "orange"]
// Custom sorting with `sort()`:
const numbers = [3, 1, 5, 2];
numbers.sort((a, b) => b - a); // Descending numerical sort
console.log(numbers); // Output: [5, 3, 2, 1]
Key Considerations:
- Compatibility: Check for toSorted() support in your target environments.
- Performance: For large arrays, toSorted() might be slightly slower due to array copying.
- Custom Sorting: Both methods offer compare functions for fine-grained control over sorting rules.
Conclusion
The choice between toSorted() and sort() hinges on whether you need to maintain the original array or prioritize in-place modification. By understanding their distinct behaviors and use cases, you can make informed decisions to write cleaner and more efficient JavaScript code.
Top comments (0)