In the normal development we often encounter the sequence of the array to sort the scene, JS gives us the sort method can be sorted array elements, by default in alphabetical order by ASCII, see the following example:
var a = [1, 3, 2, 4];
var B = [' B ', ' A ', ' C ', ' d '];a.sort ();
// [1, 2, 3, 4]
Console.log (b); [' A ', ' B ', ' C ', ' d ']
But sometimes we need to define the sort requirements ourselves, and then we can pass a function to the sort function, using the custom collation, see the following example:
var a = [1, 3, 2, 4];a.sort (function Compare (A, b) { returnA;}); Console.log (a); // [4, 3, 2, 1]
This is a simple custom example that sorts the array in descending order, for the function compare (a, b) {...} passed to the sort method, following a rule: If a positive number is returned, then A and b need to be exchanged, otherwise they will not be exchanged. Based on this criterion, we can make sure the exchange is based on our own needs. Take a look at the following code:
function Compare (A, b) { if () { /// If you do not want to exchange, return 1return -1; } return 1; // returns 1 to swap }
In this case A and B exchange or not exchange depends entirely on your own logic. You're the boss, Hee!!
If there is any wrong place, also ask you to correct your thighs!!!
Write your own JavaScript's sort function