Home >Web Front-end >JS Tutorial >JavaScript numerical array sorting example sharing_javascript skills

JavaScript numerical array sorting example sharing_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:46:50966browse

However, we will find problems during use. The array sorting method here is not sorted according to the size of the numbers we imagined, but changes the original data according to the string test results. This is not what we want.

So how can we get the sorting we want according to the size of the numbers in our minds. We can write a function ourselves to achieve this.


Copy code The code is as follows:

var values ​​= [0, 1, 5 , 10, 15];
// asc ascending function
function compareAsc(value1, value2) {
if (value1 > value2) {
return 1;
} else if (value1 < value2) {
            return -1; {
if (value1 > value2) {
return -1;
} else if (value1 < value2) {
return 1;
return 0;
}
}
values.sort(compareAsc);
console.log(values); // [0, 1, 5, 10, 15]
values.sort(compareDesc) ;
console.log(values); // [15, 10, 5, 1, 0]


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