Sorting
JS · Arrayssyntax
arr.sort(compareFn)
arr.toSorted(compareFn)example
const nums = [40, 1, 5, 200];
// WRONG: default sort is lexicographic
console.log([...nums].sort()); // [1, 200, 40, 5]
// CORRECT: numeric sort
console.log([...nums].sort((a, b) => a - b)); // [1, 5, 40, 200]
// Non-mutating sort (ES2023)
const sorted = nums.toSorted((a, b) => b - a);
console.log(sorted); // [200, 40, 5, 1]
console.log(nums); // [40, 1, 5, 200] (unchanged)Note sort() MUTATES the array and defaults to string comparison. Always pass a compare function for numbers. Use toSorted() for a non-mutating alternative.