var arr = [ {name:'a',age:9}, {name:'b',age:12}, {name:'c',age:8} ]; arr.sort((a,b)=>{ return a.age - b.age });
function compare(property){ return function(a,b){ var value1 = a[property]; var value2 = b[property]; return value1 - value2; } } console.log(arr.sort(compare('age')))
var mydate = [
{
name: "李四",
age: 15
}, {
name: "七七",
age: 26
}, {
name: "李红",
age: 7
}, {
name: "赵红",
age: 12
}]
function sortBy(attr, rev = false) {
rev = rev ? 1 : -1
return function(a,b){
a = a[attr];
b = b[attr];
if(a > b){
return rev * 1
}
else if(a < b){
return rev * -1
}
return 0
}
}
mydate.sort(sortBy('number'))
console.log(mydate)