This works directly on an array and sorts the elements within the array. If called without an argument then by default it sorts the elements alphabetically.
Example of sort()
<script language="javascript" type="text/javascript">
var names = new Array ("Tom", "Dick", "Harry");
names.sort();
// This prints out Dick,Harry,Tom
document.write(names);
</script>
Even if the array elements are numeric they are treated as strings and sorted alphabetically, which may not be what you require.
To sort them into numeric order you must pass a function as an argument (Functions are covered in the User-Defined Functions Tutorial).
The function takes two arguments - the adjacent elements within the array and compares them to decide which should appear first.
The function should return one of three results.
If the first argument (i.e. element) should appear before the second then the function should return a value less than 0.
If the first argument (i.e. element) should appear after the second then the function should return a value greater than 0.
If the first and second arguments (i.e. elements) are equal then the function should return a value of 0.
Example of Ascending Numeric sort()
<script language="javascript" type="text/javascript">
// This function returns < 0 if a < b
function compare (a, b)
{
return a-b;
}
var numbers = new Array (100, 50, 60);
numbers.sort(compare);
// This prints out 50,60,100
document.write(numbers);
</script>
Example of Descending Numeric sort()
<script language="javascript" type="text/javascript">
// This function returns > 0 if a > b
function compare (a, b)
{
return b-a;
}
var numbers = new Array (100, 50, 60);
numbers.sort(compare);
// This prints out 100,60,50
document.write(numbers);
</script>