Example of a sort () function and how to use it

Source: Internet
Author: User
This article is mainly for you to share an example of the sort () function of the principle and use of the method, has a good reference value, I hope to be helpful to everyone. Follow the small series together to see it, hope to help everyone.

The sort () method is to sort the array according to a certain condition.

The sort () method, without parameters, defaults to sorting array elements as String types in ascending order, according to their Unicode codes from small to large.

If you want to sort by your own criteria, you need to pass a comparison function.

As follows:

var arr = [' A ', ' C ', ' B '];console.log (Arr.sort ());

The value of the output is


I see an example in the red Book of JavaScript that is very good:

Let's start by creating a comparison function:

function Createcomparisonfunction (PropertyName) {     return function (object1,object2) {         var value1 = object1[ PropertyName];         var value2 = Object2[propertyname];         return value2-value1;};

Note that this value2-value1 is in descending order, and if it is value1-value2 it is sorted in ascending order

Define an array:

var data = [   {name: "Ahang", age:28},   {name: "Cao", age:29},   {name: "Bang", age:30},   {name: "Diu", age:40 }];console.log (Data.sort (Createcomparisonfunction ("Age"));

Related recommendations:

Several usages of the sort function

Sort function

C + + sort () function

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.