Sorting an array of numbers
Beginner's mistake:
javascript
const numbers = [10, 1, 3, 20];
numbers.sort();
console.log(numbers); // ["1", "10", "20", "3"] - string sortingBy default sort() converts elements to strings
and sorts them in lexicographic order ("10" comes before "2").
The correct way: with a compare function
javascript
const numbers = [10, 1, 3, 20];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 3, 10, 20]- The function
(a, b) => a - btells JavaScript how to compare numbers:- if
a - b< 0 ->acomes first - if
a - b> 0 ->bcomes first - if
a - b= 0 -> the order stays unchanged
- if
Sorting in descending order:
javascript
numbers.sort((a, b) => b - a);
console.log(numbers); // [20, 10, 3, 1]If you don't want to mutate the original array:
javascript
const arr = [5, 2, 9, 1];
const sorted = [...arr].sort((a, b) => a - b);
console.log(sorted); // [1, 2, 5, 9]
console.log(arr); // [5, 2, 9, 1] (the original is unchanged)In short:
| Task | Code | Result |
|---|---|---|
| Ascending | arr.sort((a, b) => a - b) | [1, 2, 3, 4] |
| Descending | arr.sort((a, b) => b - a) | [4, 3, 2, 1] |
| Without changing the original array | [...arr].sort(...) | a new sorted array |
Summary: To sort numbers in ascending order, always pass a compare function:
javascriptarr.sort((a, b) => a - b);
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.