sort()
method to sort the elements of the array in situ and return the arrays. The default is sorted by the Unicode code point of the string.
Grammar
Arr.sort ([comparefunction])
Parameters
-
compareFunction
-
Optional. Used to specify functions that are arranged in some order. If omitted, the element is sorted according to the Unicode bit points of the characters converted to the string.
Detailed
If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded. To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
var fruit = [' cherries ', ' apples ', ' Bananas '];fruit.sort (); [' Apples ', ' bananas ', ' cherries ']var scores = [1, 10, 2, 21]; Scores.sort (); [1, 2, 21]//Watch out comes before 2,//because ' comes before ' 2 ' in Unicode code point Order.var Thin GS = [' word ', ' word ', ' 1 word ', ' 2 Words '];things.sort (); [' 1 word ', ' 2 Words ', ' word ', ' word ']//in Unicode, numbers come before upper case letters,//which come before Lower C ASE Letters.
If you want to sort by other criteria, you need to provide a comparison function that 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 with the following return values:
- If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
- If a equals B, 0 is returned.
- If a is greater than B, a value greater than 0 is returned.
The comparer functions are as follows:
function Compare (A, b) { if (A is less than B by some ordering criterion) { return-1; } If (A is greater than B by the ordering criterion) { return 1; } A must is equal to B return 0;}
If you want to compare numbers instead of strings, the comparison function can simply be a minus B, as the following function will arrange the array in ascending order:
function Comparenumbers (A, b) {return a-a ;}
The above is used for the common sort () method, if it does not meet your needs,
Please visit: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Array.prototype.sort ()