这可能不是你想要的,但它应该给你一个足够好的想法来继续:
var list = [{
prop1: 'a',
prop2: 5
}, {
prop1: 'b',
prop2: 4
}, {
prop1: 'c',
prop2: 3
}, {
prop1: 'd',
prop2: 2
}, {
prop1: 'e',
prop2: 1
}];
function sort(propName, direction) {
var dirOffset = direction === 'desc' ? -1 : 1;
list.sort(function(a, b){
a = a[propName];
b = b[propName];
if (a === b) {
return 0;
}
var out = a < b ? -1 : 1;
return out * dirOffset;
});
}
function log(propName) {
list.forEach(function(item){
console.log(item[propName]);
});
}
function sortAndLog(propName, direction) {
console.log('Sorted by', propName, direction);
sort(propName, direction);
log(propName);
console.log('------------------------------------');
}
sortAndLog('prop1', 'desc');
sortAndLog('prop1', 'asc');
sortAndLog('prop2', 'asc');
sortAndLog('prop2', 'desc');