DEV Community

Saharat Paynok
Saharat Paynok

Posted on

Do not use array.sort() Function Without a Compare Function in JavaScript

Image description

You might need to sort their elements when working with arrays in JavaScript. The sort() function is commonly used for this purpose. However, there’s an important caveat: if you’re dealing with an array of numbers, using sort() without a compare function can yield unexpected outcomes.

The Default Behavior of sort()

By default, the sort() function treats elements as strings and compares them based on their UTF-16 code units order. This behavior works well for sorting strings alphabetically, but it falls short when sorting numbers

Example 1: Sorting Strings

Let’s say we have an array of animal names:

var animals = ["Horse", "Cat", "Tiger", "Lion"];
animals.sort(); // Result: ["Cat", "Horse", "Lion", "Tiger"]
Enter fullscreen mode Exit fullscreen mode

The strings are sorted alphabetically, which is what we expect.

Example 2: Sorting Numbers

Now, consider an array of numbers:

var numbers = [12, 10, 15, 11, 14, 13, 16];
numbers.sort(); // [10, 11, 12, 13, 14, 15, 16]
Enter fullscreen mode Exit fullscreen mode

Wait, what happened? The numbers are sorted as strings! The reason is that the default comparison treats them as such.

The Solution: Using a Compare Function

You must provide a compare function to sort numbers (or any other data type) properly. This callback function defines an alternative sorting order. It takes two arguments (often referred to as a and b) and returns either a positive, negative, or zero.

Here’s how you can create a simple compare function for sorting numbers:

function compare(a, b) {
    return a - b;
Enter fullscreen mode Exit fullscreen mode

In this function:

If a is greater than b, it returns a positive value.
If a equals b, it returns zero.
If a is less than b, it returns a negative value.
Now, let’s sort our array of numbers using this compare function:

numbers.sort(compare); // Result: [10, 11, 12, 13, 14, 15, 16]
Enter fullscreen mode Exit fullscreen mode

Perfect! The numbers are now sorted correctly.


Remember that when sorting arrays in JavaScript, especially with numbers, always use a compare function. It ensures predictable and accurate sorting behavior. Don’t rely on the default string-based sorting; take control by providing your comparison logic.

Happy coding! 🚀

Feel free to customize this article further or add any additional insights you’d like to share. If you have more requests or questions, feel free to ask! 😊👍

Top comments (0)