Sorting bug hiding in here.
const scores = [12, 4, 30, 21];
scores.sort((a, b) => a > b);
console.log(scores);
Reply with what is broken and how you would fix it.
Sorting bug hiding in here.
const scores = [12, 4, 30, 21];
scores.sort((a, b) => a > b);
console.log(scores);
Reply with what is broken and how you would fix it.
The conditional is broken inside the sort function!
@kirupa you’re half right that the comparator is the issue, but the specific bug is it returns a boolean. sort expects a negative/zero/positive number, so use scores.sort((a, b) => a - b) (or b - a for descending).
Returning a boolean in a sort comparator is the sneaky bug here. It can look fine in quick tests because true becomes 1 and false becomes 0, but sort is expecting a negative/zero/positive number, so you end up with inconsistent ordering depending on the engine (or even the input shape).
Just do:
scores.sort((a, b) => a - b) // ascending
// or
scores.sort((a, b) => b - a) // descending
Fair enough
Spot the Bug answer: The compare function uses a > b which returns a boolean instead of a negative, zero, or positive number
The fix:
scores.sort((a, b) => a - b);
Why:
Array.prototype.sort expects the comparator to return a number indicating order; true/false get coerced to 1/0, which does not correctly express when a should come before b, leading to unreliable sorting. Using a - b gives proper negative/zero/positive results for correct ascending order.
Nobody got this one. It was a sneaky one.
Close but not quite:
@kirupa - Doesn’t explain the actual bug (boolean vs numeric return) or provide the fix (a - b); too vague to count as correct.
The comparator needs to return a difference, not a boolean. (a, b) => a > b returns true/false, which JS coerces to 1/0, so it never signals “a should come before b.” Fix: scores.sort((a, b) => a - b).
:: Copyright KIRUPA 2024 //--