How to Sort by Multiple Criteria in JavaScript: Simple Guide
To sort by multiple criteria in JavaScript, use the
Array.prototype.sort() method with a custom compare function that checks each criterion in order. Return a negative, zero, or positive value for each criterion to decide the order, moving to the next criterion only if the previous one is equal.Syntax
The sort() method takes a compare function with two parameters representing elements to compare. Inside the function, return a negative number if the first element should come before the second, a positive number if after, or zero if they are equal. For multiple criteria, check each condition in sequence and return as soon as a difference is found.
javascript
array.sort((a, b) => {
if (a.firstCriterion < b.firstCriterion) return -1;
if (a.firstCriterion > b.firstCriterion) return 1;
// If equal, check second criterion
if (a.secondCriterion < b.secondCriterion) return -1;
if (a.secondCriterion > b.secondCriterion) return 1;
return 0; // all criteria equal
});Example
This example sorts an array of people first by age ascending, then by name alphabetically if ages are equal.
javascript
const people = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 30 }, { name: 'David', age: 25 } ]; people.sort((a, b) => { if (a.age < b.age) return -1; if (a.age > b.age) return 1; // ages are equal, sort by name if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); console.log(people);
Output
[
{ name: 'Bob', age: 25 },
{ name: 'David', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Charlie', age: 30 }
]
Common Pitfalls
- Not returning
0when elements are equal can cause unstable sorting. - Using subtraction for string comparison leads to
NaNresults; use comparison operators instead. - For descending order, reverse the return values or swap
aandbin comparisons.
javascript
const items = [ { score: 10, name: 'Zoe' }, { score: 10, name: 'Anna' } ]; // Wrong: subtracting strings items.sort((a, b) => a.name - b.name); // NaN, no sorting // Right: use comparison items.sort((a, b) => { if (a.score !== b.score) return b.score - a.score; // descending score if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; });
Quick Reference
Tips for sorting by multiple criteria:
- Use
sort()with a compare function. - Check criteria in priority order.
- Return
-1,1, or0properly. - Use string comparison operators for text.
- Reverse logic for descending order.
Key Takeaways
Use a custom compare function in
sort() to handle multiple criteria.Return
-1, 1, or 0 to control order for each criterion.Check each sorting criterion in sequence, moving to the next only if the previous is equal.
Use comparison operators for strings, not arithmetic operations.
Invert return values or swap parameters to sort descending.