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 comparator is returning a boolean (a > b), but Array. prototype. sort expects the compare function to return a negative number, zero, or a positive number. With a boolean you end up with inconsistent ordering because true gets coerced to 1 and false to 0, and you never return a negative value. Fix it by returning a numeric difference:
scores.sort((a, b) => a - b)
Kirupa has a decent explainer on why this matters:
kirupa. com/html5/sorting_arrays_js. htm
Spot the Bug answer: The comparator 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 represent negative differences, leading to unreliable or incorrect sort results. Using a - b gives proper numeric comparison for ascending order.
:: Copyright KIRUPA 2024 //--