Notes for sorting arrays (sort) in js

Source: Internet
Author: User

This article mainly describes the precautions for sorting arrays (sort) in js. If you need it, you can refer to it for help.

Check the Code directly. The test result is also pasted with the Code as follows: var arrDemo = new Array (); arrDemo [0] = 10; arrDemo [1] = 50; arrDemo [2] = 51; arrDemo [3] = 100; arrDemo. sort (); // After the sort method is called, the array itself will be changed, that is, the original array alert (arrDemo) will be affected; // 10,100, 50, 51 by default, the sort method is sorted in ascii alphabetical order, rather than the arrDemo which we think is sorted by number size. sort (function (a, B) {return a> B? 1:-1}); // sort alert (arrDemo) in ascending order; // 51,100, arrDemo. sort (function (a, B) {return a <B? 1:-1}); // sort alert (arrDemo) from large to small; //, 50, 10 Conclusion: 1. after the sort method is called for the array, it will affect itself (instead of generating a new array) 2. by default, the sort () method is sorted by characters. Therefore, when sorting a numeric array, you cannot take it for granted that it will be sorted by number size! 3. To change the default sort behavior (sort by characters), you can specify the sort rule function (as shown in this example)

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.