JavaScript numeric array ordering sample sharing _javascript Tips

Source: Internet
Author: User

However, we find the problem in use, where the array ordering method is not sorted according to the size of the figure we imagined, but rather the original data was changed according to the string test results. That's not what we want.

So how do we get what we want to sort by the size of the numbers in our minds? We can write a function to implement it ourselves.


Copy Code code 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]

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.