The instance code of the JS function sort

Source: Internet
Author: User
Tags sort sorted by name
This article introduces the JS function sorting code, the need for friends can refer to the copy code code as follows:


var as = [1,2,11,3434,3,4545,33,55,0];


As.sort (); This sort is sorted by dictionary


//Custom sorted by number


function Sortbynum (a,b) {


return parseint (a)-parseint (b);


}


As.sort (Sortbynum);


//Sorted 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)//sorted by name


Ps.sort (sortbyage)//sorted by age


The problem with this sort of ordering is to assume that the object has many attributes, so our program will set the rules for how many attributes are sorted separately. So there are the following methods:

Copy Code code 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;
}

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.