js 对象数组的排序问题

需求

一个对象数组,按照不同的属性进行排序
数组如下

let arr = [
  {
    index_name: '交易',
    index_value: 1897,
    biz_dt: '2023-01-10T01:37:15.000Z',
  },
  {
    index_name: '交易',
    index_value: 1000,
    biz_dt: '2023-01-10T01:38:15.000Z',
  },
  {
    index_name: '交易',
    index_value: 1669,
    biz_dt: '2023-01-09T01:38:15.000Z',
  },
]

思路

一 、根据数值进行排序

我们可以直接使用sort函数进行排序,如下:

/*
 * @Author: Tricia
 * @Date: 2023-01-30 14:37:21
 * @Description: 指标值由小到大排序
 */
let arr1 = arr.sort((a, b) => a.index_value - b.index_value)
console.log(arr1)

如下:
在这里插入图片描述

二、如果针对时间排序

比较复杂,我们可以将比较函数单独封装成一个新的函数。该函数涵盖了所有数据格式。

/*
 * @Author: Tricia
 * @Date: 2023-01-30 14:51:19
 * @Description: 获取最新时间的数据
 */
// 对象数组比较函数(默认升序)
function compareVal(k, order = 'asc') {
  // k  属性的键,order  排序方式
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(k) || !b.hasOwnProperty(k)) {
      // 该属性在任何对象上都不存在(即错误的属性)
      return 0
    }
    // 判断要对比的属性的格式,字符串还是数字
    const val1 = typeof a[k] === 'string' ? a[k].toUpperCase() : a[k]
    const val2 = typeof b[k] === 'string' ? b[k].toUpperCase() : b[k]

    let comparison = 0
    if (val1 > val2) {
      comparison = 1
    } else if (val1 < val2) {
      comparison = -1
    }
    return order === 'desc' ? comparison * -1 : comparison
  }
}

let res1 = data.sort(compareVal('biz_dt', 'desc'))
// ,res2 = data.sort(compareVal('index_value'))

console.log('res1:', res1)


如下:
res1
在这里插入图片描述

res2
在这里插入图片描述
参考:https://www.sitepoint.com/sort-an-array-of-objects-in-javascript/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

且陶陶º

感谢大人投喂~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值