前端排序,按照对象数组种某个元素进行排序

12 篇文章 0 订阅
9 篇文章 0 订阅
import _ from 'lodash'

/**
 * 数据排序
 * @param {*} origin  源数据
 * @param {*} sortKey 排序的字段
 * @param {*} type 排序方式 descending:倒序, ascending:正序
 * Rules: 将【pre】和【next】为非零Boolean值【null、undefined、''】的项移到数据最后,不参与正常排序
 */
function sortByKey(origin, sortKey, type = 'descending') {
    // 深拷贝一份原数组, 避免改变原数组(这里引入Lodash中的深拷贝函数),sort方法会改变原数组而非生成新数组
    const target = _.cloneDeep(origin)
    // 排序规则不在范围内则直接返回原数组的拷贝
    if (!['descending', 'ascending'].includes(type)) return target
    return target.sort((pre, next) => {
        let preValue = pre[sortKey]
        let nextValue = next[sortKey]
        if (!preValue && preValue !== 0) {
            preValue = type === 'descending' ? -(Math.pow(2,53) - 1) : (Math.pow(2,53) - 1)
        }
        if (!nextValue && nextValue !== 0) {
            nextValue = type === 'descending' ? -(Math.pow(2,53) - 1) : (Math.pow(2,53) - 1)
        }
        return type === 'descending' ? (nextValue - preValue) : (preValue - nextValue)
    })
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值