一.升序
//对数组进行排序
function compare(property) {
return (firstobj, secondobj) => {
const firstValue = firstobj[property];
const secondValue = secondobj[property];
return firstValue - secondValue ; //升序
};
}
二.降序
//对数组进行排序
function compare(property) {
return (firstobj, secondobj) => {
const firstValue = firstobj[property];
const secondValue = secondobj[property];
return secondValue - firstValue; //降序
};
}
其他类型数组也是这样。
三.使用
let arr = [{id:1},{id:2}];
arr = arr.sort(compare("id"));