Description
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.
The Array.Sort () method is sorted by default in ascending order, and if you want to sort by a different standard, 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.
Simple point: Compare functions two parameters A and B, return a-C ascending, return b-a descending
Here are some examples to understand
Normal Array Ascending
var arr = [4,3,6,5,7,2,1];arr.sort (); Console.log (arr); // output results [1,2,3,4,5,6,7]
Normal Data Descending
var arr = [4,3,6,5,7,2,1];arr.sort (); Arr.sort (function(A, b ) { return B-A;}); Console.log (arr); // output results [7,6,5,4,3,2,1]
Object Array Sorting
varArr= [ { ' Sortno ': 2}, { ' Sortno ': 1}, { ' Sortno ': 5}, { ' Sortno ': 6}, { ' Sortno ': 7}, { ' Sortno ': 3}, { ' Sortno ': 9}, { ' Sortno ': 4}, { ' Sortno ': 0}];arr.sort (function(A, b) {returnA.sortno-B.sortno;}); Console.log (arr);//Output Results//{' Sortno ': 2}//{' Sortno ': 1}//{' Sortno ': 5}//{' Sortno ': 6}//{' Sortno ': 7}//{' Sortno ': 3}//{' Sortno ': 9}//{' Sortno ': 4}//{' Sortno ': 0}Object array Multi-conditional ordering
(This example if the Sortno is the same, press SortNo2 from large to small)
varArr= [ { ' Sortno ': 2, ' SortNo2 ': 3}, { ' Sortno ': 1, ' SortNo2 ': 3}, { ' Sortno ': 5, ' SortNo2 ': 3}, { ' Sortno ': 6, ' SortNo2 ': 3}, { ' Sortno ': 7, ' SortNo2 ': 3}, { ' Sortno ': 3, ' SortNo2 ': 4}, { ' Sortno ': 3, ' SortNo2 ': 2}, { ' Sortno ': 3, ' SortNo2 ': 1}, { ' Sortno ': 3, ' SortNo2 ': 3}, { ' Sortno ': 8, ' SortNo2 ': 3}, { ' Sortno ': 4, ' SortNo2 ': 1}, { ' Sortno ': 4, ' SortNo2 ': 2}];arr.sort (function(A, b) {if(A.sortno = = =b.sortno) {returnB.sortno2-A.sortno2; } Else { returnA.sortno-B.sortno; }}); Console.log (arr); //Output Results//{' Sortno ': 1, ' SortNo2 ': 3}//{' Sortno ': 2, ' SortNo2 ': 3}//{' Sortno ': 3, ' SortNo2 ': 4}//{' Sortno ': 3, ' SortNo2 ': 3}//{' Sortno ': 3, ' SortNo2 ': 2}//{' Sortno ': 3, ' SortNo2 ': 1}//{' Sortno ': 4, ' SortNo2 ': 2}//{' Sortno ': 4, ' SortNo2 ': 1}//{' Sortno ': 5, ' SortNo2 ': 3}//{' Sortno ': 6, ' SortNo2 ': 3}//{' Sortno ': 7, ' SortNo2 ': 3}//{' Sortno ': 8, ' SortNo2 ': 3}
JS's sort () method