Examples of sort () usage in javascript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the usage of sort () in javascript, and analyzes the functions, definitions, and usage skills of sort, for more information about how to use sort () in javascript, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

Function Syntax:

arrayObject.sort(sortby)

You think this is not the right way but you love it

The split function is also used here to go to an array of strings, which is commonly used. Then, sort the values in the logarithm group by the sort function sort () of the array to obtain a new array. Then, the sorted string is obtained by outputting the array content cyclically.

In this example, It is sorted by ascii code by default.
What if it's a number? Try it ~

Modify the value of p as follows:

20 38 19 32 654 2 123 454 4

Running result: 123 19 2 20 32 38 4 454 654

It is sorted by character encoding, rather than the value size.

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;      });

Running result: 2 4 19 20 32 38 123 454

The above sorting is in the positive order. If it is in reverse order, you need to change it again:
Change return a-B in the function to return B-.

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 design javascript programs.

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.