Skip to main content

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 sorting

By 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 - b tells JavaScript how to compare numbers:
    • if a - b < 0 -> a comes first
    • if a - b > 0 -> b comes first
    • if a - b = 0 -> the order stays unchanged

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:

TaskCodeResult
Ascendingarr.sort((a, b) => a - b)[1, 2, 3, 4]
Descendingarr.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:

javascript
arr.sort((a, b) => a - b);

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.