Home > Web Front-end > JS Tutorial > body text

JavaScript numerical array sorting example sharing_javascript skills

WBOY
Release: 2016-05-16 16:46:50
Original
902 people have browsed it

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]


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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!