1.数组的排序,此函数只可排序数字类型
const arr = [{
a:'a',
b:12
},{
a:'b',
b:15
},{
a:'c',
b:10
},{
a:'d',
b:9
}]
function sortFn(prop){
return function(a,b){
var x = a[prop]
var y = b[prop]
return x - y
}
}
const list = arr.sort(sortFn('b'))
console.log('排序后的数组==>',list)
2.数组的排序,支持字符串排序,以编码顺序排序
const arr = [{
a:'a',
b:12
},{
a:'b',
b:15
},{
a:'d',
b:10
},{
a:'c',
b:9
}]
function sortFn(arr, sortKey = 'id') {
if (arr.length == 0) return arr
if (arr.filter(v => v[sortKey])) {
arr.sort(function (a, b) {
return a[sortKey] - b[sortKey]
})
} else {
arr = arr.sort()
}
return arr
}
const listA = sort(arr,'a')
console.log('排序后的数组A==>',listA)
const listB = sort(arr,'b')
console.log('排序后的数组B==>',listB)