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;
}