Sorting elements
Throughout this book, you will learn how to write the most used sorting algorithms. However, JavaScript also has a sorting method available which we can use without having to write our own logic whenever we need to sort arrays.
First, let's take our numbers array and put the elements out of order ([1, 2, 3, ... 10]
is already sorted). To do this, we can apply the reverse
method, in which the last item will be the first and vice versa, as follows:
numbers.reverse();
So now, the output for the numbers array will be [10, 9, 8, 7, 6, 5, 4, 3, 2, 1
]. Then, we can apply the sort method as follows:
numbers.sort();
However, if we output the array, the result will be [1, 10, 2, 3, 4, 5, 6, 7, 8, 9
]. This is not ordered correctly. This is because the sort
method in JavaScript sorts the elements lexicographically, and it assumes all the elements are strings.
We can also write our own comparison function. As our array has numeric elements, we can write the following code...