Lessons · JavaScript · sort with a comparator
Sort by the thing that matters
The comparator decides order: return negative, zero or positive. To sort by two fields, compare the first and fall through to the second.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
People by surname, tasks by priority then age, files by size: records rarely sort by their whole value.
How to think about it
If I explained the order to someone, what would I say? Say the rule in words, then write it: (a, b) => b.score - a.score || a.name.localeCompare(b.name) reads 'score descending, then name'.
Worked example
people.sort((a, b) => a.age - b.age)By age ascending.
people.sort((a, b) => b.age - a.age || a.name.localeCompare(b.name))Oldest first, ties by name.
Your turn
Sort words shortest first.
words.sort((a, b) => a.length b.length);
Solve one with the tests running
The trap
Returning true/false from a comparator. It must return a number.
Practise sort with a comparator on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.