Examples of usage of sort () in JavaScript _javascript techniques

Source: Internet
Author: User

The example in this article analyzes the use of sort () in JavaScript. Share to everyone for your reference. The specific analysis is as follows:

Syntax for functions:

Arrayobject.sort (SortBy)

You are not the right way but your love it

Here also uses the Split function, the purpose is to go to a string of arrays, more commonly used. The array's sort function is then sorted by the values in the arrays, the new array is obtained, and the sorted string is obtained by iterating through the contents of the array.

In the example, by default, it is sorted according to the ASCII code.
If it is a number, what will happen? Give it a try ~

The values in the Modify P are as follows:

20 38 19 32 654 2 123 454 4

The results of the operation are: 123 19 2 20 32 38 4 454 654

It is sorted by character encoding, not the size of the numeric value.

If you want to sort numbers, you need to write a few more lines of code:

The modified code is as follows:

Originarr = Originarr.sort (function (a,b) {return      
  a-b;      
});

Run Result: 2 4 19 20 32 38 123 454 654

The above sort is sorted in a positive order, if it is in reverse order, then you need to change it again:
The return a-b in the function can be changed to b-a.

If the alphabet is sorted, the changed code is as follows:

Originarr = Originarr.sort (function (a,b) { 
  if (a > B) return-1; 
  if (a < b) return 1; 
  return 0; 
});

I hope this article will help you with your JavaScript programming.

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.