We know that the sort method of the array can sort the array elements. By default, the elements are sorted in the ASCII alphabetic order. If you want to sort by other sequence, you need to provide a comparison function as a parameter for the sort method. Here we will talk about how to write this comparison function. For example:
Var a = [1, 5, 3, 7];
A. sort (function (a, B) {return B-a}); // arranged from big to small
Then how should we write this comparison function for the order of complex points.
For the comparison function f (a, B) {...}, if a positive number is returned, it means that a and B need to be exchanged; otherwise, it is not exchanged. Therefore, we can write the comparison function in the following format:
The Code is as follows:
Function f (a, B ){
If (...){
Return 1;
}
Return-1;
}
Then, what we need to do is to write the conditions in the if statement. This condition is the condition that a and B need to be exchanged. For example, var a = ["a", "A", "B", "B"]; is case-insensitive and sorted from large to small, only when. toString (). toLowerCase () <B. toString (). when toLowerCase () is used, a and B are exchanged, so use this to fill in the if condition. The comparison function is:
Function f (a, B ){
If (a. toString (). toLowerCase () <B. toString (). toLowerCase ()){
Return 1;
}
Return-1;
}
For example, to arrange the elements of an array in the order of odd numbers and even numbers, if a and B are required for exchange, only if a is an even number and B is an odd number, sort the values from small to large only when the values a and B are odd or even and a> B. As follows:
<Script type = "text/javascript"> var a = [1, 7, 3, 9, 5, 6, 2, 8, 4]; function f (a, B) {if (0 = a % 2 & 1 = B % 2) {return 1 ;} if (1 = a % 2 & 1 = B % 2 | 0 = a % 2 & 0 = B % 2) & a> B) {return 1;} return-1;} alert (. sort (f); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Author: JayChow