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 Sort 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)//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;
}