Definition and usage
sort() method is used to sort the elements of array.
Syntax
arrayObject.sort(sortby)
Parameters | Description |
sortby | Optional. Specifies the sort order. Must be a function. |
Return value
A reference to the array. Please note that the array is sorted on the original array, no copy is made.
Description
If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order. To be more precise, they will be sorted in the order of character encoding. To achieve this, the elements of the array should first be converted into strings (if necessary) for comparison.
If you want to sort by other criteria, you need to provide a comparison function, which compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b, and its return value is as follows:
If a is less than b, a should appear before b in the sorted array, then return a value less than value of 0.
If a is equal to b, return 0.
If a is greater than b, return a value greater than 0.
Example
Example 1
In this example, we will 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 + "<br />") document.write(arr.sort()) </script>
Output:
George,John,Thomas,James,Adrew,Martin Adrew,George,James,John,Martin,Thomas
Example 2
In this example, we will create an array and sort it alphabetically:
<script type="text/javascript"> 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 + "<br />") document.write(arr.sort()) </script>
Output:
10,5,40,25,1000,1 1,10,1000,25,40,5
Please note that the above code does not sort the numbers according to the size of the value. To achieve this, you must use a sorting function:
<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 + "<br />") document.write(arr.sort(sortNumber)) </script>
Output:
10,5,40,25,1000,1 1,5,10,25,40,1000
Use js The sort() method sorts numbers
<script> var arr = [23,12,1,34,116,8,18,37,56,50]; alert(arr.sort(); </script>
returns:
[1, 116, 12, 18, 23, 34, 37, 50, 56, 8]
The above is the detailed content of JavaScript method sort() to sort elements of an array. For more information, please follow other related articles on the PHP Chinese website!