0
0
JavascriptHow-ToBeginner · 3 min read

How to Custom Sort in JavaScript: Simple Guide with Examples

In JavaScript, you can custom sort an array by passing a compare function to the sort() method. This function takes two elements and returns a number to decide their order, allowing you to define any sorting logic you want.
📐

Syntax

The sort() method can take an optional compare function that defines the sort order.

  • array.sort(compareFunction): Sorts the array using the logic in compareFunction.
  • compareFunction(a, b): Returns a negative number if a should come before b, zero if they are equal, or a positive number if a should come after b.
javascript
array.sort((a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});
💻

Example

This example shows how to sort an array of numbers in descending order using a custom compare function.

javascript
const numbers = [5, 2, 9, 1, 5, 6];
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[9, 6, 5, 5, 2, 1]
⚠️

Common Pitfalls

One common mistake is not providing a compare function when sorting numbers, which causes sort() to convert numbers to strings and sort lexicographically.

Another pitfall is returning incorrect values from the compare function, which can lead to unexpected order.

javascript
const nums = [10, 2, 30];
// Wrong: no compare function, sorts as strings
nums.sort();
console.log(nums); // Output: [10, 2, 30]

// Right: with compare function for numeric sort
nums.sort((a, b) => a - b);
console.log(nums); // Output: [2, 10, 30]
Output
[10, 2, 30] [2, 10, 30]
📊

Quick Reference

  • sort(): Sorts array in place.
  • compareFunction(a, b): Returns negative if a < b, zero if equal, positive if a > b.
  • Use b - a for descending numeric sort.
  • Always provide a compare function for numbers or custom objects.

Key Takeaways

Use a compare function with sort() to define custom sorting logic.
Return negative, zero, or positive values in the compare function to control order.
Without a compare function, sort() converts elements to strings and sorts lexicographically.
For numeric descending order, use (a, b) => b - a as the compare function.
Always test your compare function to avoid unexpected sorting results.