js排序问题
1、直接排序
var arr = [1,3,2,5];
function compare(a,b){
return a - b;//从小到大
return b - a;//从大到小
}
console.log(arr.sort(compare));
2 嵌套排序
按照数组中的某一项value值进行排序,property为属性值
var arr = [
{name:'jim',age:27},
{name:'tony',age:40},
{name:'jane',age:36},
{name:'lilei',age:23},
{name:'Hmm',age:28},
{name:'jack',age:56},
{name:'vivian',age:19}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value2 - value1;
}
}
console.log(arr.sort(compare('age')))
3 嵌套排序,且可以切换正反序
var arr = [
{name:'willm',age:27},
{name:'jay',age:40},
{name:'Ljj',age:36}
];
//不传rev的,则默认按升序排列,传rev则按降序排列
function compare(property,rev){
if( rev == undefined ){
rev = 1;
}else{
rev = -1;
}
return function(a,b){
var value1 = a[property];
var value2 = b[property];
if(value1 < value2){
return rev * -1;
}
if(value1 > value2){
return rev * 1;
}
return 0;
}
}
console.log(arr.sort(compare('age')));