Skip to content

How to Fix Array.sort Not Sorting Correctly in JavaScript

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Array.sort Not Sorting Correctly in JavaScript. We cover key concepts, practical examples, and best practices.

The Problem

Array.sort() without a compare function converts elements to strings and sorts lexicographically, causing numbers to sort as [1, 10, 2, 20] instead of [1, 2, 10, 20].

Quick Fix

Step 1: Provide a numeric compare function

Default sort converts numbers to strings:

const nums = [10, 2, 5, 1, 20];
nums.sort();
console.log(nums);
[1, 10, 2, 20, 5]

Add a compare function:

const nums = [10, 2, 5, 1, 20];
nums.sort((a, b) => a - b);
console.log(nums);
[1, 2, 5, 10, 20]

For descending order:

nums.sort((a, b) => b - a);
console.log(nums);
[20, 10, 5, 2, 1]

Step 2: Sort strings case-insensitively

Default string sort is case-sensitive (uppercase first):

const words = ['banana', 'Apple', 'cherry'];
words.sort();
console.log(words);
['Apple', 'banana', 'cherry']

Use localeCompare for case-insensitive sorting:

const words = ['banana', 'Apple', 'cherry'];
words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(words);
['Apple', 'banana', 'cherry']

Step 3: Sort objects by property

For objects, access the property in the compare function:

const users = [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 25 },
    { name: 'Charlie', age: 35 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
[
    { name: 'Bob', age: 25 },
    { name: 'Alice', age: 30 },
    { name: 'Charlie', age: 35 }
]

Step 4: Stable sort (ES2019)

ES2019 guarantees stable sort, but for consistent behavior:

const items = [
    { value: 1, group: 'A' },
    { value: 2, group: 'B' },
    { value: 3, group: 'A' }
];
items.sort((a, b) => a.group.localeCompare(b.group));
console.log(items);

Prevention

  • Always provide a compare function for numeric arrays.
  • Use localeCompare for string arrays to handle accents and case.
  • Sort objects by extracting the property in the compare function.
  • Test sorting with edge cases (negative numbers, decimals, empty values).
  • Use toSorted() in modern JS to avoid mutating the original array.

Common Mistakes with sort error

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does Array.sort mutate the original array?

Array.sort sorts in place by default, modifying the original array. If you want a sorted copy without mutation, use toSorted() (ES2023) in modern environments, or manually copy: [...array].sort(compareFn). To avoid bugs, always treat sort as a mutating operation.

How do I sort by multiple criteria?

Chain comparisons using logical OR: array.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name)). The compare function returns the first non-zero result. If a.age - b.age is 0 (equal), it falls through to the name comparison.

What compare function should I use for floating point numbers?

Use a - b for floating point numbers as well. This works correctly because the subtraction produces the exact difference, which the sort algorithm uses to determine order. For values near the limits of precision, use explicit comparisons: if (a < b) return -1; if (a > b) return 1; return 0;.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro