Array.sort() : Sort « Array « JavaScript Tutorial






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>








11.29.Sort
11.29.1.Array.sort()
11.29.2.Sort a string array
11.29.3.Array.sort is case sensitive
11.29.4.Using the sort() method on numbers and strings
11.29.5.Array.sort() with custom sorter
11.29.6.Using an alphabetical sort() method on strings
11.29.7.Using the sort() method on numbers and strings with custom sorter
11.29.8.Case-insensitive comparison