Sample Code of js function sorting

Source: Internet
Author: User

Copy codeThe Code is as follows:
Var as = [,];
As. sort (); // sort by dictionary
// Customize the order by number
Function sortByNum (a, B ){
Return parseInt (a)-parseInt (B );
}
As. sort (sortByNum );
// Sort by Object
// Define a person object
Function Person (name. age ){
This. name = name;
This. age = age;
}
Var p1 = new Person ("zhang1", 11 );
Var p2 = new Person ("zhang2", 1 );
Var p3 = new Person ("zhang3", 18 );
Var p4 = new Person ("zhang4", 13 );
Var ps = [p1, p2, p3, p4];
Function sortByName (obj1, obj2 ){
If (obj1.name> obj2.name) {return 1}
Else if (obj1.name = obj2.name) {return 0}
Else {return-1}
}
Function sortByAge (obj1, obj2 ){
Return obj1.age-obj2.age;
}
Ps. sort (sortByName) // sort by name
Ps. sort (sortByAge) // sort by age

The problem brought about by the above sorting is that if the object has many attributes, then our program will set the sorting rules for the attributes respectively. Therefore, the following method is available:
Copy codeThe Code is as follows:
Function sortByProperty (proName ){
Var sortFun = function (obj1, obj2 ){
If (obj1 [proName]> obj2 [proName]) {return 1}
Else if (obj1 [proName] = obj2 [proName]) {return 0}
Else {return-1}
}
Return sortFun;
}

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.