将对象数组按照某个键值排序
2022-04-22 本文已影响0人
秘果_li
arr=[{key:3,name:'name3'}, {key:2,name:'name2'}, {key:1,name:'name1'}, ]
function compare(property: any) {
return (a: any, b: any) => {
const value1 = a[property];
const value2 = b[property];
return value1 - value2;
};
}
arr.sort(compare('key'));
// 输出 arr=[{key:1,name:'name1'}, {key:2,name:'name2'}, {key:3,name:'name3'},]