Javascript Array - sort method


The sort() method can be used to sort the items of an array. If the array consists of the no numeric words the sort method is straight forward. You can specify the order of sort - either ascending or descending and it will sort the array. By default the order is ascending and the sorting is done alphabetically. The things get complicated when you sort numerically. We will come to that shortly. Before that, take a look at the following example.


<html>
<body>

<script type="text/javascript">


var cars = ["Toyota", "Honda", "Audi"];
cars.sort();
document.writeln('Car brands :' + cars + '<br />');

</script>

</body>
</html>



Try this example online here .

This gives expected result. However, if you try the same thing on numbers you get something unexpected. Take a look at the following example.


<html>
<body>

<script type="text/javascript">


var numbers = [5,20,243,334,9,34,13];
document.writeln('Original Numbers :' + numbers + '<br />');
numbers.sort();
document.writeln('Sorted Numbers :' + numbers + '<br />'); // Outputs 13,20,243,334,34,5,9

</script>

</body>
</html>



Try this example online here .
As you can see, this method sorts not based upon the "value" but upon the order. So how to fix it ? Fortunately, sort method can take an argument. And that argument is a fuction ( NOTE ). This functions determines how we compare the elements of the array to determine the sort order. The example below will make the things clearer.


<html>
<body>

<script type="text/javascript">
function compare(x, y) {
   
   if (x < y) {
      return -1;
   }
   if (x > y) {
      return 1;
   }
   if (x == y) {
      return 0;
   }
}

var numbers = [5,20,243,334,9,34,13];
document.writeln('Original Numbers :' + numbers + '<br />');
numbers.sort(compare);
document.writeln('Sorted Numbers :' + numbers + '<br />');

</script>

</body>
</html>



Try this example online here .

As you can see this codes gives the desired result
Original Numbers :5,20,243,334,9,34,13
Sorted Numbers :5,9,13,20,34,243,334			 


To sort the element in the revese order, you can either change the function or apply the reverse method. We will discuss the reverse method in the next post.