Find the bug · #55 · Sort and search Easy JavaScript
“Low to high” puts ₹1,200 first
The “Price: low to high” filter puts expensive items before cheap ones.
On this page
The report
The “Price: low to high” filter on the shop puts a ₹1,200 item before a ₹25 one, and ₹5 after ₹25.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Sorts prices from low to high for the "Price: low to high" filter.
function sortPrices(prices) {
return [...prices].sort();
}Read it, then pick a line.
With no compare function, how does JavaScript’s sort compare two numbers?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(sortPrices([999, 25, 1200, 5]).join(', '));It prints
1200, 25, 5, 999
It should print
5, 25, 999, 1200
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 calls sort() with no compare function. JavaScript then converts every value to a string and sorts alphabetically: “1200” comes before “25” because “1” comes before “2”. Pass a numeric compare function, (a, b) => a - b.
The fix
1// Sorts prices from low to high for the "Price: low to high" filter.2function sortPrices(prices) {3 return [...prices].sort();3 return [...prices].sort((a, b) => a - b);4}How you’d find it
- Reproduce with prices of different lengths: 1200, 25, 5, 999. The order is alphabetical, not numeric.
- Alphabetical order means the values were compared as text. Check what
sort()does by default: converts to strings. - Give it a compare function that returns a negative, zero or positive number.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.deepEqual(sortPrices([10, 9, 100]), [9, 10, 100]);
assert.deepEqual(sortPrices([]), []);Where else this bites
- Sorting version numbers or file names that contain numbers.
- Python and Java sort numbers numerically by default; JavaScript is the odd one out.