需求
一个对象数组,按照不同的属性进行排序
数组如下
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/