Multi-Level Sorting
What you'll learn: How to sort arrays by multiple criteria, applying secondary sorting rules when the primary field values match.
The Core Idea
Sometimes sorting by a single field isn't enough. Imagine sorting a contact list: you want it alphabetized by last name, but when two people share the same last name, you want them ordered by first name. That's multi-level sorting—your comparator checks the primary field first, and only when those values are equal does it move on to compare the secondary field.
How It Works
Your comparator function returns the comparison result for the primary field. But if that result is 0 (meaning the values are equal), you return the comparison for the secondary field instead:
const people = [
{ last: "Smith", first: "Zoe" },
{ last: "Smith", first: "Alice" },
{ last: "Jones", first: "Bob" }
];
people.sort((a, b) => {
// Primary: sort by last name
if (a.last < b.last) return -1;
if (a.last > b.last) return 1;
// Secondary: if last names equal, sort by first name
if (a.first < b.first) return -1;
if (a.first > b.first) return 1;
return 0; // completely equal
});
// Result: Jones-Bob, Smith-Alice, Smith-Zoe
Adding More Levels
You can chain as many levels as needed. Just keep checking: if the current comparison returns 0, move to the next field:
employees.sort((a, b) => {
// Level 1: department
if (a.dept < b.dept) return -1;
if (a.dept > b.dept) return 1;
// Level 2: seniority (descending)
if (a.years > b.years) return -1;
if (a.years < b.years) return 1;
// Level 3: name
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
Key Takeaway: Multi-level sorting uses comparators that cascade through multiple fields—only checking the next field when the previous comparison returns 0 (equal values).