Sorting an array of integers is something that we’ve to a lot in our JavaScript app.
In this article, we’ll look at how to sort an array of integers correctly in our JavaScript app.
Array.prototype.sort
The sort
method lets us sort an array by passing in a comparator function.
To use it to sort numbers, we write:
const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => a - b);
console.log(sorted)
to do an ascending sort.
So sorted
is [1, 2, 3, 4]
.
The numbers will be swapper if the callback’s return value is positive, so we get them sorted in ascending order.
To sort in descending order, we just swap a
and b
in the expression we return:
const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => b - a);
console.log(sorted)
We must use sort
with the callback so that we can compare the numbers.
Then sorted
is [4, 3, 2, 1]
.
If we don’t pass in a callback, then sort
assumes that we’re sorting strings.
And it’ll try to sort items alphabetically.
We can just use Math.sign
to return -1 for if an argument is a negative number, 0 if the argument is 0, and 1 if the number is positive.
So we can write:
const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(a - b));
console.log(sorted)
to sort ascending.
And:
const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(b - a));
console.log(sorted)
to sort descending.
Conclusion
To sort an JavaScript array with numbers correctly, we should pass in a comparator function to compare the numbers if we use sort
.
Otherwise, it’ll assume that we’re sorting strings and will try to sort the items alphabetically.