var arr = [
{name:'zopp',age:0},
{name:'gpp',age:18},
{name:'yjj',age:8}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age')))
如何根據參數不同,來確定是升序排列,還是降序排序呢?
/**數組根據數組對象中的某個屬性值進行排序的方法
* 使用例子:newArray.sort(sortBy('number',false)) //表示根據number屬性降序排列;若第二個參數不傳遞,默認表示升序排序
* @param attr 排序的屬性 如number屬性
* @param rev true表示升序排列,false降序排序
* */
sortBy: function(attr,rev){
//第二個參數沒有傳遞 默認升序排列
if(rev == undefined){
rev = 1;
}else{
rev = (rev) ? 1 : -1;
}
return function(a,b){
a = a[attr];
b = b[attr];
if(a < b){
return rev * -1;
}
if(a > b){
return rev * 1;
}
return 0;
}
}
