Sort the pits in the sorting

Source: Internet
Author: User

The cause of the problem:

In the post of an inside question, many people use the sort () method to sort the array. Seemingly reasonable code, the result of the operation is frequently wrong. Why is it? Because a lot of people miss out a little bit, that is sort () sorted by default in ASCII alphabetical order, rather than according to our assumed number size.

The problem arises:

For example, we use the sort () array [ -12,3,6,5,100] to sort in ascending order, so what is the result? [ -12,100,3,5,6]. The array [ -12,10,3,6,5] is sorted in ascending order? The answer is [ -12,10,3,5,6]. Sort the array [ -12,70,3,5,6]? [ -12,3,5,6,70] The result is equal to the size of the data.

Workaround:

Although sort () does not sort by number, it has always been a ploy, and we can specify the collation function by changing the default sort behavior (arranged by character):

For example: Arr.sort (A, B) {return-A-A;});( From small to Large) arr.sort (function (A, b) {return b-a;}); (from large to small)

There are also collation functions such as Arr.sort (A, b) {return a>b?1:-1}) (from small to Large) arr.sort (function (A, b) {return a>b?1:-1}) (from large to small)

The specific code is as follows:

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title></title>6<script type= "Text/javascript" >7        8          vararr =NewArray ("abbbbbbb", "BCCCC", "Dhacker", "Efff", "FJJJ", "", "ghhh", "Hoo");9 Arr.sort ();Ten           for(vari = 0; i < arr.length; i++) { One Document.writeln (Arr[i]); A          } -  -          varNumarr =NewArray (12,23,100,4,23,34,2,-15); the         //Numarr.sort (function compare (A, b) {return-A-B;}); -Numarr.sort (function(A, B) {returnA>b?-1:1}) -  -           for(vari = 0; i<numarr.length; i++) { +document.write (Numarr[i] + "<br>"); -          } +  A alert (Numarr); at  -</script>> -  - -<body> -  in</body> -

  

  

  

Sort the pits in the sorting

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.