JavaScript will sort numbers by first digit which means 10 will be before 2, 20 will be before 3, and so on. The get around this, we supply the sort() method with a function that does simple arithmetic to help get the order correct.
> y = [42, 73, 101, 27, 10, 1, 2]
> console.log(y.sort())
<- Array(7) [ 1, 10, 101, 2, 27, 42, 73 ]
Using subtraction, a - b
will give ascending order,
> y = [42, 73, 101, 27, 10, 1, 2]
> console.log(y.sort((a, b) => a - b))
<- Array(7) [ 1, 2, 10, 27, 42, 73, 101 ]
b - a
will give descending order,
> y = [42, 73, 101, 27, 10, 1, 2]
> console.log(y.sort((a, b) => b - a))
<- Array(7) [ 101, 73, 42, 27, 10, 2, 1 ]
Simple logic will also work. a > b
, for ascending order, a < b
for descending order.
> y = [42, 73, 101, 27, 10, 1, 2]
> console.log(y.sort((a, b) => a > b))
<- Array(7) [ 1, 2, 10, 27, 42, 73, 101 ]
> console.log(y.sort((a, b) => a < b))
<- Array(7) [ 101, 73, 42, 27, 10, 2, 1 ]