JavaScript Array Method : sort()

The JavaScript sort() method sorts the elements of an array. The basic syntax of sort() method is :
  array.sort( compareFunction );
Where the compareFunction is optional, which Specifies a function that defines the sort order. If compareFunction is omitted, then the array is sorted lexicographically. For example :
<script> 
  var vagitables = ["Potato", "Onion", "Tomato", "Apple", "Mango", "Banana", "brinjal"];
  document.write("Vagitables : " + vagitables + "<br/>");
  var sorted = vagitables.sort();
  document.write("Vagitables (sorted) : " + sorted);
</script>
Output :


Numeric sort :

When we try to sort the numeric values with above method then it did not works, because it tries to sort() the numbers in lexicographical order. Now to sort the numbers we can use compareFunctions. For example to sort numbers in ascending order we can use below function :
  function(a, b){return a - b}
And to sort numbers in descending order we can use :
  function(a, b){return b - a}
Example :
<script> 
  var numbers = [60, 50, 200, 90, 120, 20, 30, 160, 190, 140];
  document.write("Numbers : " + numbers + "<br/>");
  var sorted_asc = numbers.sort(function(a, b){return a - b});
  document.write("Sorted in Ascending Order: " + sorted_asc + "<br/>");
  var sorted_dsc = numbers.sort(function(a, b){return b - a});
  document.write("Sorted in Descending Order : " + sorted_dsc + "<br/>");
</script>
Output :


Next Topic :