toSorted() in Javascript ES2023

Similar to the existing sort method, toSorted() sorts the elements of an array. However, it has two key differences: -

  1. Immutability: Unlike sort which modifies the original array in-place, toSorted creates a new sorted array, leaving the original one untouched. This is crucial for maintaining immutability in your code, promoting predictability and easier debugging.
  2. Comparison function: You can optionally provide a comparison function as an argument to toSorted. This function determines the order of the elements in the sorted array. This offers more flexibility compared to sort's default sorting behavior.

Example of Simple usage: sort numbers ascending


const numbers = [5, 2, 8, 1];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers);

Output

Script.js

Example. Sorting objects by a specific property

const users = [
  { name: "John", age: 30 },
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 },
];
const sortedUsers = users.toSorted((a, b) => a.age - b.age); 
console.log(sortedUsers);


Output

Console

Example. with a custom comparison function

const strings = ["apple", "banana", "orange"];
const sortedStrings = strings.toSorted((a, b) => b.length - a.length); 
console.log(sortedStrings);

Output

Custom comparison function

Benefits of toSorted()

  • Immutability: Encourages predictable and less error-prone code.
  • Flexibility: More control over sorting behavior with the optional comparison function.
  • Clarity: Improves code readability by separating sorting logic from the original array.

Note.  toSorted() is supported in most modern JavaScript engines and TypeScript starting from version 5.2.