Javascript Array object sort () method

Source: Internet
Author: User
Tags javascript array

Javascript Array object sort () method

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

Syntax
ArrayObject. sort (sortby)
Sortby is optional. Specify the sorting order. Must be a function.
The sort () method returns a reference to the array. Note that arrays are sorted on the original array without generating copies.
If no parameter is used when this method is called, the elements in the array are sorted alphabetically. More precise, the elements are sorted by character encoding.
To achieve this, first convert the elements of the array into strings (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 indicating the relative sequence of the two values.
The comparison function should have two parameters, a and B. The returned values are as follows:
? If a is less than B, a should appear before B in the sorted array, then a value smaller than 0 is returned.
? If a is equal to B, 0 is returned.
? If a is greater than B, a value greater than 0 is returned.

Example 1
Create an array and sort it alphabetically:

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

Output:
George, John, Thomas, James, Adrew, Martin
Adrew, George, James, John, Martin, Thomas

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

<script type="text/javascript">function sortNumber(a,b){ return a - b}var arr = new Array(6)arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write(arr + "
")document.write(arr.sort()+ "
")document.write(arr.sort(sortNumber))</script>

Output:


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.