Sorting array objects in JS (method sort () details)

Source: Internet
Author: User

Definition and Usage

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

Grammar

arrayobject. Sort (sortby)

Parameter sortby: Optional. Specifies the sort order. Must be a function.

return value

A reference to an array. Note that the array is sorted on the original array, and no replicas are generated.

normal array Ordering:

JS uses the method sort () to sort the array. The sort () method has an optional parameter, which is the function used to determine the order of the elements. If this argument is omitted, then the elements in the array will be sorted in ASCII character order . Such as:

The ASCII values of the letters A and B are 65, 66 respectively, and the values of A and B are 97 and 98 respectively, so the result of the above output is ["A", "B", "A", "B"]

If an array element is a number, it is also sorted by sort () to see how the effect looks:

There is no effect (sort by size), in fact, the sort method calls the ToString () method of each array item, gets the string, and then sorts the resulting string. Although the value is 15:3 large, "15" is preceded by "3" (ASCII character order) when a string comparison is made. Obviously, the result is not what we want, and then the parameter of the sort () method plays a role, and we call this parameter a comparison function.

The comparison function receives two parameters, returns a negative number if the first argument should precede the second, and returns 0 if the two arguments are equal, or returns a positive number if the first argument should be in the second one.

Array Object ordering:

An array item is an object that needs to be sorted against an array of an attribute of an item of the list. Actually, it's similar to the previous comparison function.

Here is an example of my project:

Now I want to sort the px field size, I do this:

Sorting array objects in JS (method sort () details)

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.