Sort and Search
3. Sorting Numeric Values
Using the sort() method, the array values are taken as strings. Thus, the sort() method will result in an incorrect output when sorting numbers. For example, if you sort the number 2 and 10. The number 10 will come first before 2. In order to fix this, a compare function must be added.
For example:
<body>
<h1> JavaScript Array Sort </h1>
<h4> Click the button to sort the array in ascending order </h4>
<button onclick="myFunctionA()">Sort as String</button>
<button onclick="myFunctionB()">Sort as Number</button>
<p id="demo"></p>
<script>
var points = [5, 10, 1, 25, 100, 40];
document.getElementById("demo").innerHTML = points;
function myFunctionA() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunctionB() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
</body>
In the example above, two buttons can be clicked. It is the "Sort as String" and "Sort as Number". When the "Sort as String" is clicked, it arranges the array by comparing the ASCII value of the characters in each element. When the two elements have the same ASCII value for its first element, then it compares the value of the second character until the characters are not the same anymore. Because of this, the numerical value is disregarded. Meanwhile, when the other button is clicked, the array is sorted according to its numerical value. See sample output below:

The compare function works as an alternative way to sort arrays. When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned value. This function returns negative, zero or positive. A negative result will sort a before b. Meanwhile, b is sorted before a when the result is positive while no changes will happen if result is 0.
The array is sorted in ascending order. In order to reverse it, little modification of the compare function can be done.
Instead of
function(a, b){return a - b}
you can change it to
function(a, b){return b - a}