treasure-sorter.js
JavaScript
π‘ Comparators return: β number β a first, + number β b first
sort = you write the rules
vault shelf
LIVE
π Shown
8
π° Priciest
β
πͺ Cheapest
β
π The Vault (array)
πͺ vault after .sort() β read it left to right: [0], [1], [2]...
πͺ€ MISSION: The Number Trap β try plain .sort() on numbers!
var scores = [80, 9, 100];
scores.sort(); // no comparator... β βββ
scores.sort((a, b) => a - b); β [9, 80, 100] β
scores.sort(); // no comparator... β βββ
scores.sort((a, b) => a - b); β [9, 80, 100] β
π± Plain .sort() compares items as TEXT: "100" < "80" < "9" (just like "1" < "8" < "9" in the dictionary)! That's why YOU must always hand it a comparator like (a, b) => a - b for numbers. πͺ€ Dodged!