JavaScript Array toSorted()

2 min read .

JavaScript arrays are powerful and versatile, and with the introduction of new methods like toSorted(), managing arrays has become even more efficient. The toSorted() method offers a way to sort arrays without mutating the original, making it ideal for scenarios where immutability is essential. In this guide, we’ll explore the toSorted() method in detail, including its syntax, use cases, and practical examples.

1. What is the toSorted() Method?

The toSorted() method is a non-mutating method that returns a new array sorted according to the specified comparison function. Unlike the traditional sort() method, toSorted() leaves the original array unchanged, making it a valuable tool in functional programming and other contexts where immutability is important.

Syntax:

let sortedArray = array.toSorted([compareFunction]);
  • compareFunction (optional): A function that defines the sort order. If omitted, the array elements are converted to strings and sorted in ascending order.

Return Value: A new array containing the sorted elements of the original array.

2. Key Differences Between toSorted() and sort()

The primary difference between toSorted() and sort() is that toSorted() does not modify the original array, whereas sort() does. This non-mutating behavior of toSorted() is crucial in situations where you need to preserve the original data.

Example:

const numbers = [5, 3, 8, 1];

const sortedNumbers = numbers.toSorted();

console.log(sortedNumbers); 
// Output: [1, 3, 5, 8]

console.log(numbers); 
// Output: [5, 3, 8, 1]

In this example, the toSorted() method returns a new sorted array, while the original array remains unchanged.

3. Practical Use Cases for toSorted()

  • Immutable Data Handling: In applications where data immutability is a priority, toSorted() provides a way to sort arrays without altering the original dataset.
  • Functional Programming: toSorted() aligns with functional programming principles by returning new data structures rather than modifying existing ones.

Example:

const students = [
  { name: 'Alice', grade: 85 },
  { name: 'Bob', grade: 92 },
  { name: 'Charlie', grade: 88 }
];

const sortedByGrade = students.toSorted((a, b) => b.grade - a.grade);

console.log(sortedByGrade);
/* Output:
[
  { name: 'Bob', grade: 92 },
  { name: 'Charlie', grade: 88 },
  { name: 'Alice', grade: 85 }
]
*/

console.log(students);
/* Original array remains unchanged:
[
  { name: 'Alice', grade: 85 },
  { name: 'Bob', grade: 92 },
  { name: 'Charlie', grade: 88 }
]
*/

4. Using Custom Compare Functions

The toSorted() method allows you to define custom sorting logic using a compare function. This is particularly useful for sorting complex data structures, such as objects.

Example:

const words = ['banana', 'apple', 'cherry'];

const sortedWords = words.toSorted((a, b) => a.length - b.length);

console.log(sortedWords); 
// Output: ['apple', 'banana', 'cherry']

In this example, the words are sorted by length, demonstrating how toSorted() can be customized with a compare function.

5. Real-World Applications

  • User Interface Elements: Sort lists of UI elements, such as tables or dropdown menus, without affecting the underlying data.
  • Data Analysis: Create sorted views of datasets for analysis while keeping the original data intact.
  • Version Control: Maintain different versions of sorted data without altering the original array, useful in scenarios like versioning systems.

6. Performance Considerations

While toSorted() is generally efficient, it does require additional memory to store the new array. When working with large datasets, be mindful of the potential impact on performance and memory usage.

Conclusion

The toSorted() method is a powerful addition to JavaScript’s array handling capabilities, offering a way to sort arrays immutably. Whether you’re working with complex datasets, implementing sorting logic in a functional programming context, or simply need to preserve the original array, toSorted() provides a robust and flexible solution.

See Also

chevron-up