Array Sorting
Overview
Sorting arrays in JavaScript is famously unintuitive for beginners. The .sort() method mutates the original array and sorts elements in place.
However, by default, .sort() converts all elements to strings and sorts them alphabetically based on UTF-16 values. This works great for strings, but catastrophically fails for numbers unless you provide a "Compare Function".
Syntax
const fruits = ["Banana", "Orange", "Apple"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Orange"]
// reverse() simply flips the current order
fruits.reverse();
console.log(fruits); // ["Orange", "Banana", "Apple"]const nums = [40, 100, 1, 5, 25];
nums.sort();
// Wait! Output: [1, 100, 25, 40, 5]
// Why? Because '100' comes before '25' alphabetically!const nums = [40, 100, 1, 5, 25];
// Provide a Compare Function!
// Ascending Order
nums.sort((a, b) => a - b);
console.log(nums); // [1, 5, 25, 40, 100]
// Descending Order
nums.sort((a, b) => b - a);Common Pitfalls
- Forgetting that
.sort()mutates the original array! If you have a list of high scores and you sort them, the original chronological order is permanently lost. Always copy the array first if you need to preserve the original:const sorted = [...scores].sort();
Interview Questions
(a, b) => a - b works.The sort method passes two elements (a, b) to the function. If the result is negative, a is sorted before b. If positive, b is sorted before a. If 0, no changes are made. Therefore, a - b guarantees smaller numbers bubble to the front.
By accessing that property inside the compare function. For example: users.sort((a, b) => a.age - b.age);
Real-World Example
Sorting an e-commerce product list by 'Price: Low to High'.
const sortedProducts = [...products].sort((a, b) => a.price - b.price);Check Your Knowledge
Test your understanding of Array Sorting with these quick questions.