Sorting An Array Of Numbers In JavaScript

JavaScript

09/08/2021


JavaScript offers a built-in function called sort that makes sorting incredibly easy. Take numbers as an example.

JAVASCRIPT
const numbers = [150, 38, 2000, -4]
numbers.sort() // Array(4) [ -4, 150, 2000, 38 ]

By default, the function will treat any array elements as strings, and consequently sort them alphabetically. 🔤 To sort numerically, we need to pass in a callback function that compares two numbers at a time.

The sort method modifies the original array.

JAVASCRIPT
numbers.sort((a, b) => a - b) // Ascending sort
numbers.sort((a, b) => b - a) // Descending sort

The comparison happens by subtracting one number from the other, which will result in 3 possible outcomes:

  • If the calculation returns less than 0, nothing happens,
  • If greater than 0, a and b switch places, and
  • If equals to 0, the order of a and b with respect to each other remains unchanged, but changes in relation to the rest of the array.

WRITTEN BY

Code and stuff