Array.sort() : Sort : Array JAVASCRIPT TUTORIALS


JAVASCRIPT TUTORIALS » Array » Sort »

 

Array.sort()


















Syntax








array.sort()
    array.sort(function)



The sort() method rearranges the elements of the array based on a sorting order.

If the method has no parameters, JavaScript attempts to convert all the elements of the array to strings and then sort them alphabetically.

If the array should be sorted some other way, a function must be provided to handle the new sorting algorithm.

The function specified must operate based on the following rules:

The function must accept two arguments that are to be compared.

The function must return a number indicating the order of the two arguments in relation to each other.

If the first argument should appear before the second argument, a number less than zero should be returned from the function.

If the first argument should appear after the second argument, a number greater than zero should be returned from the function.

If both arguments are equivalent, zero should be returned from the function.

The following example sorts Array Based on Argument Lengths












<html>
    <script language="JavaScript">
    <!--
    function contentsOfArray(theArray)
    {
      document.write("the array contains:<br>");
      for(i=0; i<theArray.length; i++)
      {
        document.write("Position ",i," = ",theArray[i],"<br>");
      }
    }
    function sortOnArgLen(arg1,arg2)
    {
      if(arg1.length < arg2.length)
        return -1;
      if(arg1.length > arg2.length)
        return 1;
      if(arg1.length == arg2.length)
        return 0;
    }
    shapes = new Array("A","B","C");
    document.write("Before the sort method ");
    contentsOfArray(shapes);
    shapes.sort(sortOnArgLen);
    document.write("<br>After the sort method ");
    contentsOfArray(shapes);
    --></script>
    </html>







HTML code for linking to this page:

Follow Navioo On Twitter

JAVASCRIPT TUTORIALS

 Navioo Array
» Sort