Sorting an array is one of those classic tasks in computer science that’s always good to review once in a while.
If you want to sort an array alphabetically (also known as lexical order) you can use the built-in sort() method.
const arr = ['Billy', 'Bob', 'Alice']; arr.sort(); // ['Alice', 'Billy', 'Bob'] arr.sort().reverse(); // ['Bob', 'Billy', 'Alice']
For an array of integers you need to use the optional
compareFunction that comes along with
sort(). It specifies a function that defines the default order. In other words, we need to provide this function ourself.
Given two elements
b being compared in
compareFunction, if the result is less than 0,
a comes first. If the result is greater than 0,
b comes first.
Therefore to sort in ascending order we use
a - b but for descending order we use
b - a.
const numArr = [1, 5, 0, 11, 25, 40]; numArr.sort(); // [0, 1, 11, 25, 40, 5] numArr.sort((a,b) => a - b); // [0, 1, 5, 11, 25, 40] numArr.sort((a,b) => b - a); // [40, 25, 11, 5, 1, 0]