Sorting arrays
suggest changeUse toSorted() when the original array should remain unchanged. It accepts the same comparison function as sort():
const numbers = [100, 1, 20, 3];
const ascending = numbers.toSorted((a, b) => a - b);
const descending = numbers.toSorted((a, b) => b - a);
console.log(numbers); // [100, 1, 20, 3]
console.log(ascending); // [1, 3, 20, 100]
console.log(descending); // [100, 20, 3, 1]
sort() uses the same ordering rules but mutates and returns the original array. Use it only when in-place mutation is intended.
Without a comparison function, elements are converted to strings and ordered by UTF-16 code units. This usually gives surprising results for numbers:
[100, 1, 20, 3].toSorted(); // [1, 100, 20, 3]
For human-readable strings, use localeCompare() or reuse an Intl.Collator when sorting many values:
const names = ['Émile', 'Ada', 'zoë', 'Åke'];
const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
const sortedNames = names.toSorted(collator.compare);
Sort objects by a property in the comparison function:
const users = [
{ name: 'Grace', score: 92 },
{ name: 'Linus', score: 87 },
{ name: 'Ada', score: 99 },
];
const ranked = users.toSorted((a, b) => b.score - a.score);
A comparison function should return a negative number when a belongs before b, a positive number when a belongs after b, and zero when their ordering is equal. It should be pure, deterministic, and transitive.