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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:24:02
Original
967 people have browsed it

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
Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
Where is js written?
From 1970-01-01 08:00:00
0
0
0
js addClass not working
From 1970-01-01 08:00:00
0
0
0
js file code not found
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template