Sorting
Sort and its surprise.
Sorting sounds simple. But JavaScript's sort has a famous surprise, which catches almost every beginner. Let's see it, and the fix.

- Sorting sounds simple
- A famous surprise
- And the fix
Sorting numbers
Sort with no arguments sorts the names alphabetically, which is fine. But numbers get sorted as text, so one hundred comes before twenty five. The fix is a compare function. A minus B sorts small to large, and B minus A sorts large to small. Run it.
const names = ["Cara", "ana", "Ben"];
console.log(names.sort());
const nums = [25, 100, 3];
console.log(nums.sort());
console.log(nums.sort((a, b) => a - b));
console.log(nums.sort((a, b) => b - a));[ 'Ben', 'Cara', 'ana' ] [ 100, 25, 3 ] [ 3, 25, 100 ] [ 100, 25, 3 ]
Two more surprises
Notice that capital letters sorted before small ones, so ana came last. To sort words naturally, use a compare function with local compare. And sort changes the original array. To keep the original, copy it first, or use the newer to sorted method, which returns a sorted copy.
| key | value |
|---|---|
| sort() | sorts as text |
| (a, b) => a − b | numbers, small first |
| localeCompare | natural word order |
| toSorted() | sorted copy |
Summary
Sort compares items as text unless you give it a compare function. For numbers, use A minus B. Next, map, which transforms every item.
Key takeaways- Pass a compare function
- a − b ascending
- toSorted keeps the original