sort()

The sort() method sorts the contents of the given array according to a defined sorting order. If the method is given no parameters, the contents of the array will be converted to strings and sorted alphabetically, A at the top and Z at the bottom. If a function is stated as the parameter, the sorting directions must adhere to the following set of basic rules and conditions.

1. The function must accept the two arguments that are to be compared, and which will define the type of sorting to be carried out.

2. The function must return a number indicating the order in which the item will exist within the newly shuffled array.

3. If the first argument appears before the second argument, a value less than 0 (zero) must be returned from the function - a negative integer.

4. If the first argument appears after the second argument, a value more than 0 (zero) must be returned from the function - a positive integer.

5. If both of the given arguments evaluate to exactly equal, zero must be returned from the function.

It should be noted that when the function evaluates both arguments as exactly equal, the order in which they will appear within the newly shuffled array will be in the same order they were before the shuffle, relatively. That is, if they were separated by two positions before the shuffle, they will be separated by two positions after the shuffle.

syntax:

array.sort()

array.sort(function)

EXAMPLE

var theArray = new Array("zebra", "armidillo", "horse");



document.write("The content order of the array is " + theArray[0] + ", " + theArray[1] + ", " + theArray[2] + "
");



var shuffledArray = theArray.sort();



document.write("The new content order of the array is " + theArray[0] + ", " + theArray[1] + ", " + theArray[2] );

The example starts with the creation of a new array called theArray. It is loaded with three values, which are string values because they are encapsulated within quotes. The array is then written to the screen through the use of a document.write statement. The array is then shuffled through the use of the sort() method. Since no function was created to sort the array items, the default action is to arrange the items alphabetically. Since the values of the array items are already strings, no conversion must take place. The second document.write statement then writes the newly shuffled contents of the array to the screen. The output should look as follows:



The content order of the array is zebra, armidillo, horse

The new content order of the array is armidillo, horse, zebra