How to Use Sort with Comparator in JavaScript
Use the
sort() method with a comparator function that takes two arguments and returns a number. Return a negative number if the first argument should come before the second, zero if they are equal, or a positive number if the first should come after. This lets you control how the array elements are ordered.Syntax
The sort() method can take a comparator function as an argument. This function compares two elements and decides their order.
array.sort(comparator): Sorts the array using the comparator.comparator(a, b): Function that compares two elementsaandb.- Return
< 0ifashould come beforeb. - Return
0ifaandbare equal in order. - Return
> 0ifashould come afterb.
javascript
array.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});Example
This example sorts an array of numbers in ascending and descending order using comparator functions.
javascript
const numbers = [5, 2, 9, 1, 5, 6]; // Sort ascending numbers.sort((a, b) => a - b); console.log('Ascending:', numbers); // Sort descending numbers.sort((a, b) => b - a); console.log('Descending:', numbers);
Output
Ascending: [1, 2, 5, 5, 6, 9]
Descending: [9, 6, 5, 5, 2, 1]
Common Pitfalls
One common mistake is not returning the correct values from the comparator, which can cause unexpected sorting results. For example, returning true or false instead of numbers does not work as expected. Also, forgetting to handle equality by returning 0 can cause unstable sorting.
javascript
// Wrong comparator (returns boolean, not number) const arr = [3, 1, 2]; arr.sort((a, b) => a > b); console.log('Wrong:', arr); // Unexpected order // Correct comparator arr.sort((a, b) => a - b); console.log('Correct:', arr);
Output
Wrong: [3, 1, 2]
Correct: [1, 2, 3]
Quick Reference
Remember these tips when using sort() with a comparator:
- Comparator must return a number, not boolean.
- Negative number means first argument comes first.
- Zero means elements are equal in order.
- Positive number means first argument comes after.
- Use subtraction for numeric sorting.
Key Takeaways
Always provide a comparator function that returns a number to control sort order.
Return negative, zero, or positive values to indicate order between two elements.
Use subtraction (a - b) for simple numeric ascending sort.
Avoid returning boolean values in the comparator; it causes incorrect sorting.
Handle equality by returning zero to keep stable sorting.