var arr = [
{sum:4,class:1},
{sum:135,class:2},
{sum:30,class:3},
{sum:19,class:4},
{sum:50,class:5},
]
function compare(propertName) {
return function (obj1, obj2) {
var value1 = obj1[propertName];
var value2 = obj2[propertName];
if(value2<value1){
return 1;
}else if(value2>value1){
return -1
}else{
return 0;
}
}
}
结果:
[ { sum: 4, class: 1 },
{ sum: 19, class: 4 },
{ sum: 30, class: 3 },
{ sum: 50, class: 5 },
{ sum: 135, class: 2 } ]
console.log(arr.sort(compare("sum"))