js函数封装-数组排序(1)

183 阅读1分钟

1.数组的排序,此函数只可排序数字类型

//原始数据
const arr = [{
        a:'a',
        b:12
    },{
        a:'b',
        b:15
    },{
        a:'c',
        b:10
    },{
        a:'d',
        b:9
    }]
//排序函数
//prop为排序字段名,如示例中字段b
function sortFn(prop){
    return function(a,b){
        var x = a[prop]
        var y = b[prop]
        return x - y // x - y 为升序,y - x 为降序,可以根据需求封装,或者通过第二个入参控制升序降序 
    }
}
//函数使用方法
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
}

// 针对字段a排序
const listA = sort(arr,'a')
console.log('排序后的数组A==>',listA)
// 针对字段b排序
const listB = sort(arr,'b')
console.log('排序后的数组B==>',listB)