Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Sort JavaScript Arrays Immutably with `toSorted()`

1 min read .
Sort JavaScript Arrays Immutably with `toSorted()`

toSorted() returns a sorted copy of an array without modifying the original. It is the non-mutating counterpart to sort().

Basic Usage

For numbers, provide a comparator because the default sort order is based on strings:

const numbers = [5, 3, 8, 1];
const sortedNumbers = numbers.toSorted((a, b) => a - b);

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

Sort Objects

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);
console.log(students); // unchanged

Sort Strings with a Custom Rule

const words = ['banana', 'apple', 'cherry'];
const sortedWords = words.toSorted((a, b) => a.length - b.length);

For locale-aware alphabetical ordering, use localeCompare:

const names = ['Zoë', 'Alice', 'Álvaro'];
const sorted = names.toSorted((a, b) => a.localeCompare(b));

toSorted() vs. sort()

sort() changes the array in place. toSorted() creates a new array, which is useful in state-management and functional-style code where accidental mutation can cause bugs.

Compatibility

For older runtimes that do not support toSorted(), use:

const sorted = [...numbers].sort((a, b) => a - b);

Conclusion

Use toSorted() when you need sorted data while preserving the source array. Remember to provide a comparator for numeric or domain-specific ordering, and account for the extra allocation when working with very large arrays.

Related Posts

chevron-up