1、需要排序的数组
let testData = [
{name:'张三',age:30,salary:5000},
{name:'李四',age:50,salary:6000},
{name:'王五',age:20,salary:7000},
{name:'赵六',age:40,salary:4000}
];
2、排序方法
const compare = (property, orderType) => {
return function (a, b) {
var value1 = a[property];
var value2 = b[property];
return orderType === 'up' ? value1 - value2 : value2 - value1;
};
}
3、调用方法进行升序
testData.sort(compare('age', 'up'));
排序后结果:
4、调用方法进行降序
testData.sort(compare('age', 'down'));
排序后结果