JavaScript numeric array sorting example _ javascript tips-js tutorial

Source: Internet
Author: User
In Javascript, we know that there are two methods for directly sorting Arrays: reverse () and sort (). Reverse () sorts arrays in reverse order, while sort () sorts arrays in forward order. However, we will find the problem in use. The array sorting method here is not sorted by the number size we imagined, but to change the original data according to the string test results. This is not what we want.

So how can we get what we want to sort by the number size in our thinking. We can compile a function for implementation.


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;
} Else {
Return 0;
}
}
// Desc descending Function
Function compareDesc (value1, value2 ){
If (value1> value2 ){
Return-1;
} Else if (value1 <value2 ){
Return 1;
} Else {
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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.