sort With a Comparator (Finally Explained)

Grade 10, page 8 of 12. A one-minute read.

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 returnsMeaning
A negative numbera should come before b
A positive numberb should come before a
ZeroThey'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:

JavaScript
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:

JavaScript
const byName = [...players].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((p) => p.name));

It prints

[ 'Chloe', 'Felix', 'Hugo' ]

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning