js实现多列排序-存在问题

js实现多列排序

根据业务逻辑调整 sortData 的数据。
排序的规则是按照第一列排序,第一列相同按照第二列排序,依次类推

// 要排序的数据
const array = [{ name: '甲'asd, age: 10, money: 100 }, { name: '亿', age: 10, money: 90 }, { name: '丙', age: 9, money: 100 }]

// 排序的顺序,和升序降序  descending,ascending
const sortData = [{ orderColumn: 'age', orderState: 'ascending' }, { orderColumn: 'money', orderState: 'descending' }]


array.sort((a, b) => {
    const sortFun = (index) => {
        const currentSort = sortData[index]
        // 如果当前相同,则递归向下排序
        if (a[currentSort.orderColumn] === b[currentSort.orderColumn]) {
            // 如果没有下级了,直接按照当前层级进行排序
            if (sortData.length - 1 >= index + 1) {
                return sortFun(index + 1)
            }
        }
        // 根据排序规则进行排序
        if (currentSort.orderState === 'ascending') {
            return Number(a[currentSort.orderColumn]) - Number(b[currentSort.orderColumn])
        } else {
            return Number(b[currentSort.orderColumn]) - Number(a[currentSort.orderColumn])
        }
    }
    // 排序递归方法
    return sortFun(0)
})


console.log(array)


posted @ 2023-07-14 14:31  聂显达  阅读(187)  评论(1编辑  收藏  举报