var as = [1,2,11,3434,3,4545 ,33,55,0];
as.sort(); //This sorting is based on dictionary sorting
//Customized sorting based on numbers
function sortByNum(a,b){
return parseInt(a) - parseInt(b);
}
as.sort(sortByNum);
//Sort by objects
//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 caused by the above sorting is that assuming that the object has many attributes, then how many attributes should our program have? Set the sorting rules separately. So there is the following method:
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;
}