Why does [10, 9, 1].sort() return [1, 10, 9] in JavaScript?
By default sort converts elements to strings and compares them in dictionary order, so "10" comes before "9". Pass a comparator such as (a, b) => a - b to sort numbers numerically.
Explain it simply
Sorting words in a dictionary: "apple" comes before "banana" letter by letter. The default sort() treats every element like a word. Comparing the text "10" and "9", the first character "1" is smaller than "9", so "10" comes first.
A comparator function fixes this. It receives two values and returns a negative number if the first should go earlier, positive if later, and zero if equal. a - b does exactly that for numbers.
Example
const nums = [10, 9, 1];
console.log([...nums].sort()); // Output: [1,10,9]
console.log([...nums].sort((a, b) => a - b)); // Output: [1,9,10]
console.log([...nums].sort((a, b) => b - a)); // Output: [10,9,1]Complexity
Sorting is O(n log n) time either way; copying the array first adds O(n) space.
What to say in the interview
"The default sort compares values as strings, so numbers sort lexicographically. I pass a comparator, a minus b for ascending or b minus a for descending. Also, sort mutates the original array, so I copy it first if I need the original order."
Common mistakes
- Forgetting that sort changes the original array.
- Writing a comparator that returns a boolean, such as a > b, which does not work correctly.