JavaScript Array Object Sort () method

Source: Internet
Author: User
Tags javascript array

The sort () method is used to sort elements of an array.

Grammar
Arrayobject.sort (SortBy)
SortBy is optional. Specifies the sort order. Must be a function.
The sort () method returns a reference to an array. Note that the array is sorted on the original array, and no replicas are generated.
If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded.
To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number that describes the relative order of the two values.
The comparison function should have two parameters A and B with the following return values:
If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
If a equals B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.

Example 1
Create an array and sort alphabetically:

<script type= "Text/javascript" >var arr = new Array (6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "Jame S "arr[4] =" Adrew "arr[5] =" Martin "document.write (arr +" <br/> ") document.write (Arr.sort ()) </script>

Output:
George,john,thomas,james,adrew,martin
Adrew,george,james,john,martin,thomas

Example 2
Create an array and sort by alphabetical order and by numeric size:

<script type= "Text/javascript" >function Sortnumber (A, b) {return A-b}var arr = new Array (6) arr[0] = "ten" arr[1] = "5 "Arr[2] =" arr[3] = "arr[4" = "arr[5" = "1" document.write (arr + "<br/>") document.write (Arr.sort () + "< br/> ") document.write (Arr.sort (sortnumber)) </script>

Output:
10,5,40,25,1000,1
1,10,1000,25,40,5
1,5,10,25,40,1000

JavaScript Array Object Sort () method

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.