contents   index   previous   next

Array sort()




compareFunction - identifier for a function which expects two parameters x and y, and returns a negative value if x < y, zero if x = y, or a positive value if x > y.



object - this Array object after being sorted.



This method sorts the elements of the array. The sort is not necessarily stable (that is, elements which compare equal do not necessarily remain in their original order). The comparison of elements is done based on the supplied compareFunction. If compareFunction is not supplied, then the elements are converted to strings and compared. Non-existent elements are always greater than any other element, and consequently are sorted to the end of the array. Undefined values are also always greater than any defined element, and appear at the end of the Array before any empty values. Once these two tests are performed, then the appropriate comparison is done.


If a compare function is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:


If compareFunction(a, b) is less than zero, sort b to a lower index than a.

If compareFunction(a, b) returns zero, leave a and b unchanged relative to each other.

If compareFunction(a, b) is greater than zero, sort b to a higher index than a.


By specifying the following function as a sort function, you will get the desired result when comparing numbers:

function compareNumbers(a, b) 


   return a ? b



Clib strcmp()



// Consider the following code,

// which sorts based on numerical values,

// rather than the default string comparison.


function compare( x, y )


   x = ToNumber(x);

   y = ToNumber(y);


   if( x < y )

      return -1;

   else if ( x == y )

      return 0;


      return 1;



   var array = new Array( 3, undefined, "4", -1 );




// Prints out the sorted array,

// which is "-1,3,4,,".

//  Notice the undefined value

// at the end of the array.


Array splice()