How to Fix Array.sort Not Sorting Correctly in JavaScript
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
localeComparefor 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
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro