The principle and use of the sort () method in JS

Source: Internet
Author: User

The sort () method is used to sort the elements of an array and to return arrays. The default sort order is based on the string Unicode code. Because sorting is sorted in the order of the string Unicode codes, the array elements should first be converted to strings (if necessary) for comparison.

Syntax: Arrayobject.sort (sortby);

The parameter sortby is optional and is used to specify the order of sorts, but it must be a function.

Example one: Sort by alphabetical order

Example two: or Sort by letter

Nani, this sort of doesn't seem to get the results you want ...

If you want to get the results you want, either ascending or descending, you need to provide a comparison function. The function compares the size of 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, that is, a-a is less than 0, a value less than 0 is returned, and the array is sorted in ascending order.

If a equals B, 0 is returned.

If a is greater than B, that is, a-a is greater than 0, a value greater than 0 is returned, and the array is sorted in descending order.

Example three: ascending order

Example four: Descending sort

What if you want to sort by a property value in an Array object???

Example five: Sort by an attribute value in an array object

Example six: Depending on the parameter to determine whether ascending or descending

Reprint: https://www.cnblogs.com/saifei/p/9043821.html

The principle and use of the sort () method in JS

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.