const list = [
{
"orderNo": "1",
},
{
"orderNo": "10",
},
{
"orderNo": "2",
},
{
"orderNo": "3",
},
{
"orderNo": "4",
}
]
// 自定义排序方法 数组对象按key升序或者降序排列
const compareValues = (key, order = 'asc') => {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
// const comparison = a[key]?.localeCompare(b[key]);
const comparison = a[key] - b[key]
// console.log(1.localeCompare(10))
return order === 'desc' ? comparison * -1 : comparison;
};
};
console.log(list.sort(compareValues('orderNo')))
///[ { orderNo: '1' },{ orderNo: '2' },{ orderNo: '3' },{ orderNo: '4' },{ orderNo: '10'}]
自定义排序方法 数组对象按某个key升序或者降序排列
最新推荐文章于 2024-10-30 19:10:39 发布