In Grade 7, we told you to memorize (a, b) => a - b for sorting numbers. Now you know enough to understand it!
sort takes a comparison function (a callback). While sorting, it picks pairs of items, a and b, and asks your function: "which of these should come first?" Your function answers with a number:
| Your function returns | Meaning |
|---|---|
| A negative number | a should come before b |
| A positive number | b should come before a |
| Zero | They're equal, keep their order |
So (a, b) => a - b works like this: if a is smaller, a - b is negative, so a goes first. That gives smallest-to-largest order. Swap it to b - a for largest-to-smallest.
Now we can sort arrays of objects by any property:
const players = [
{ name: "Hugo", points: 42 },
{ name: "Chloe", points: 87 },
{ name: "Felix", points: 65 },
];
const leaderboard = [...players].sort((a, b) => b.points - a.points);
leaderboard.forEach((p, i) => console.log(`${i + 1}. ${p.name} - ${p.points}`));
It prints
1. Chloe - 87 2. Felix - 65 3. Hugo - 42
(We used [...players] to sort a copy, because sort changes the original array. Remember that from Grade 7?)
For sorting by text, use the string method localeCompare, which returns a negative, positive or zero number just like we need, and handles uppercase, lowercase and accented letters properly:
const byName = [...players].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((p) => p.name));
It prints
[ 'Chloe', 'Felix', 'Hugo' ]