Home >Web Front-end >JS Tutorial >How to write the comparison function of JS array sort_javascript skills

How to write the comparison function of JS array sort_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:24:02943browse

For example:
var a=[1,5,3,7];
a.sort(function(a, b) { return b-a});//Arrange from large to small
Then if it is complicated How should we write this comparison function in the order of points?
For the comparison function function f(a,b){...}, if a positive number is returned, it means that a and b need to be exchanged, otherwise they will not be exchanged. So we can write comparison functions according to the following format:

Copy code The code is as follows:

function f(a, b) {
if (...) {
return 1;
}
return -1;
}

Then , all we have to do is write the condition in if, this condition is the condition that needs to be exchanged to return a and b. For example: var a=["a","A","B","b"]; is case-insensitive and sorted from large to small, only if a.toString().toLowerCase() < b When .toString().toLowerCase(), 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;
}
Another example: if you want to arrange the elements of the array in the order of odd numbers first and then even numbers, then if a and b need to be exchanged, only if a is an even number and b is The odd number condition is sufficient, and then sorted from small to large, only when a and b are both odd or even numbers and a>b. As follows:

[Ctrl A Select All Note: If you need to introduce external Js, you need to refresh to execute
]
Author: JayChow
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn