Skip to content

Array.sort default lexicographic order

Quick summary

You called .sort() on a number array without a comparator — it sorted as strings, so [10, 2, 1] becomes [1, 10, 2].

Why this happens

  • Calling .sort() with no argument on a number array

  • Assuming numeric sort is the default

  • Sorting objects without a comparator that reads the sort key

Minimal example

✗ Broken code
const nums = [10, 2, 1, 21];
nums.sort(); // lexicographic!
console.log(nums); // [1, 10, 2, 21]
✓ Fixed code
const nums = [10, 2, 1, 21];
nums.sort((a, b) => a - b); // numeric
console.log(nums); // [1, 2, 10, 21]

Without a comparator, sort converts to strings and orders lexicographically, so '10' < '2'. Passing (a, b) => a - b sorts numerically.

How to diagnose

  • Print the sorted array and check for surprising order (10 before 2)

  • Confirm whether a comparator was passed to .sort

  • Test with [10, 2, 1].sort() to see the lexicographic result

How to fix

  • Pass a comparator: arr.sort((a, b) => a - b) for numbers

  • For objects: arr.sort((a, b) => a.key - b.key)

  • Use localeCompare for string sorting with locale awareness

How to prevent

  • Always pass a comparator to .sort for non-string arrays

  • Write a quick test that checks the sorted order

Related Resources

Related Glossary

Related Lessons

← Back to language