Javascript Array object sort () method
The sort () method is used to sort the elements of an array.
Syntax
ArrayObject. sort (sortby)
Sortby is optional. Specify the sorting order. Must be a function.
The sort () method returns a reference to the array. Note that arrays are sorted on the original array without generating copies.
If no parameter is used when this method is called, the elements in the array are sorted alphabetically. More precise, the elements are sorted by character encoding.
To achieve this, first convert the elements of the array into strings (if necessary) for comparison.
If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number indicating the relative sequence of the two values.
The comparison function should have two parameters, a and B. The returned values are as follows:
? If a is less than B, a should appear before B in the sorted array, then a value smaller than 0 is returned.
? If a is equal to B, 0 is returned.
? If a is greater than B, a value greater than 0 is returned.
Example 1
Create an array and sort it alphabetically:
<script type="text/javascript">var arr = new Array(6)arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"arr[3] = "James"arr[4] = "Adrew"arr[5] = "Martin"document.write(arr + "
")document.write(arr.sort())</script>
Output:
George, John, Thomas, James, Adrew, Martin
Adrew, George, James, John, Martin, Thomas
Example 2
Create an array in alphabetical order and sort by number size:
<script type="text/javascript">function sortNumber(a,b){ return a - b}var arr = new Array(6)arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write(arr + "
")document.write(arr.sort()+ "
")document.write(arr.sort(sortNumber))</script>
Output: