Array.sort() (Method)

Sort the elements in an array.


ECMAScript edition - 2
JavaScript - 1.1
JScript - 3.0
Internet Explorer - 4.0
Netscape - 3.0
Netscape Enterprise Server - 2.0
Opera - 3.0
Property/method value type:Array object
JavaScript syntax:-myArray.sort()
Argument list:aComparatorA function object that will compare two items and returns a flag indicating their order in the sort collating sequence.

The elements in the array are sorted in place and the sorted array is returned as a result of this method. The argument provides a comparator function to determine the relationship between any two items.

The comparator function is necessary if you want to sort into any order other than alphabetically ascending. You can observe the operation of the comparator by placing document.write() methods into its source text. These will demonstrate how the comparison is called during the sort.

In the example, a comparator function shows how to custom sort items. The example demonstrates sorting by length rather than charset collation sequence. You must make sure the comparator returns one of the following three values:

You can reverse the sort direction by negating the result returned by this comparator function.

In the example, a more highly optimised comparator is shown as well. The more lengthy version is presented first to illustrate the algorithmic requirements of the comparator, but the second is functionally identical and can be accomplished in one line and therefore the sort is much faster.

The result of this method is the array with its elements sorted according to the comparator.


Example code:

   // Demonstrate array joins
   myString1 = "This is a sentence made of words.";
   document.write("Original input string<BR>")
   myArray = myString1.split(" ");
   document.write("<BR><BR>String split into an array<BR>")
   document.write("<BR><BR>Array sorted<BR>")
   myString2 = myArray.join(" ");
   document.write("<BR><BR>Array joined up as a string<BR>")
   // Comparator function
   function compare(aValue1, aValue2)
      if(aValue1.length < aValue2.length)
         return -1;
      if(aValue1.length > aValue2.length)
         return 1;
      return 0;
   // Optimised comparator function
   function optimalCompare(aValue1, aValue2)
     return (aValue1.length - aValue2.length);
   // Display an array in a table
   function displayArrayAsTable(anArray)
      myLength = anArray.length;
      document.write("<TABLE BORDER=1>");
      for(myIndex = 0; myIndex < myLength; myIndex++)

See also:Array.prototype, JellyScript

insert figure 0014


ECMA 262 edition 2 - section -

ECMA 262 edition 3 - section -