AI Hints
Home›JavaScript Tutorial›Searching and Sorting
JavaScript · Lesson 48 of 138

Sorting

Sort and its surprise.

⏱ 2 min read▶ Video at 58:27🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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

Sorting
From the video: Sorting
  • 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.

app.jsjavascript
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));
Output
[ '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.

keyvalue
sort()sorts as text
(a, b) => a − bnumbers, small first
localeComparenatural 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
Next up: map — transform every item