Why does [10, 9, 1].sort() give [1, 10, 9], and how do you sort numbers correctly?
By default sort converts items to strings and compares them in dictionary order, so "10" comes before "9". Pass a comparator like (a, b) => a - b to sort numbers. Note that sort changes the original array.
Explain it simply
A dictionary does not know that 10 is bigger than 9. It compares letter by letter: "1" comes before "9", so "10" lands before "9". That is exactly what sort() does without help, because it turns every element into a string first.
To sort by value, give it a comparator: a function that returns a negative number if a should come first, positive if b should, and zero if they tie. For ascending numbers use a - b; for descending use b - a.
sort also changes the array in place and returns that same array.
Example
console.log([10, 9, 1].sort()); // Output: [1,10,9]
console.log([10, 9, 1].sort((a, b) => a - b)); // Output: [1,9,10]
console.log([10, 9, 1].sort((a, b) => b - a)); // Output: [10,9,1]
const marks = [3, 1, 2];
const sorted = marks.sort((a, b) => a - b);
console.log(sorted === marks); // Output: true
console.log(marks); // Output: [1,2,3]What to say in the interview
"Default sort compares string forms, so numbers come out in lexicographic order. I pass (a, b) => a - b for numbers. sort mutates the original array, so I copy first with [...arr] or use toSorted when I need to keep the input."
Common mistakes
- Writing a comparator that returns a boolean (a > b). It must return a number.
- Forgetting that the original array is changed.