Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Why does JavaScript sort 10 before 2 in my list of session lengths?

Technology category photographTechnology

The sample session lengths are the numbers 2, 10 and 3. My page calls `lengths.sort()` and displays 10, 2, 3. I checked the input: these are number values, not strings copied out of form fields.

I expected a numerical order and started looking for a conversion bug. MDN says the default sort compares string representations; it also notes that sort changes the original array. MDN's sort reference

What's the smallest sensible correction here? The sorted list is for display, while another part of the exercise still needs the original sequence in which the sessions were entered.

Discussion

5 community replies

For the finite numbers in your example, a numeric comparison such as `(a, b) => a - b` supplies the ascending order you intended. Being number values doesn't make the no-argument sort choose that comparison automatically.

Protect the original sequence too. MDN documents `toSorted()` for producing a sorted array without mutating the original, and also describes copying an array before calling sort. Choose a supported approach for your page rather than fixing only the displayed order.

The conversion check wasn't wasted: it establishes what input the correction is meant to handle. Keep the scope to those numerical session lengths. If later inputs can be missing or invalid, decide how to handle them rather than assume this comparator defines that policy.

Keep a small example that verifies both requirements: the display order should be 2, 3, 10, and the original sequence should remain 2, 10, 3. Looking only at the sorted output would miss the second mistake.

Include a repeated length as another ordinary case once that works. You don't need a large testing framework for this little exercise; a few explicit expected sequences will make the intended behaviour easier to preserve as the page changes.

Join the discussion

More in Technology