我有这个对象数组:
[
{
id: 1,
timestamp1: Date,
timestamp2: Date,
timestamp3: Date
},
{
id: 2,
timestamp1: Date,
timestamp2: Date,
timestamp3: Date
}.
...
]
我想按最新日期对数组进行排序,比较所有 3 个对象属性并为每个对象使用最新的属性。
提前给你加油。
答案 0 :(得分:3)
通过查看 js sort
documentation,您会看到排序将函数作为参数:
知道了这一点,让我们一起构建函数:
首先,我们想获得对象的最高日期。
为此,我建议使用 Math.max,它接受一个数组并返回最大的参数。
这里有效,因为 js 将日期理解为整数。
function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}
现在让我们构建排序函数。
function compare(a,b){
return highestDate(b) - highestDate(a)
}
这是一个用于测试的狙击手:
function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}
function compare(a,b){
return highestDate(b) - highestDate(a)
}
let obj1={
id:1,
timestamp1 : new Date(2001,1,1),
timestamp2 : new Date(2002,1,1),
timestamp3 : new Date(2003,1,1) //third highest date
}
let obj2={
id:2,
timestamp1 : new Date(1997,1,1),
timestamp2 : new Date(2004,1,1),//second highest date
timestamp3 : new Date(2003,1,1)
}
let obj3={
id:3,
timestamp1 : new Date(1991,1,1),
timestamp2 : new Date(2001,1,1),
timestamp3 : new Date(2005,1,1) //highest date
}
let arr = [obj1,obj2,obj3]
console.log(arr.sort(compare))
答案 1 :(得分:2)
我们可以使用 Object.values 和 Math.Max 找到每个对象的最大时间戳。
创建一个函数来查找这些值 getMaxTimestamp
,我们可以在 array.sort() 中使用它来按最大时间戳对对象进行排序:
const arr = [ { id: 1, timestamp1: new Date('2021-07-01T16:00:00Z'), timestamp2: new Date('2021-03-01T08:00:00Z'), timestamp3: new Date('2018-10-08T19:00:00Z') }, { id: 2, timestamp1: new Date('2019-08-01T16:00:00Z'), timestamp2: new Date('2015-09-21T08:00:00Z'), timestamp3: new Date('2017-10-08T19:00:00Z') }, { id: 3, timestamp1: new Date('2024-01-01T16:00:00Z'), timestamp2: new Date('2015-09-21T08:00:00Z'), timestamp3: new Date('2021-10-08T19:00:00Z') } ]
function getMaxTimestamp(obj) {
const timestamps = Object.values(obj).filter(v => v instanceof Date);
return Math.max(...timestamps);
}
const result = arr.sort((a,b) => {
return getMaxTimestamp(a) - getMaxTimestamp(b);
})
console.log("Result:",result)
答案 2 :(得分:0)
只需使用 Array.sort() 并尝试此 question 中的比较函数。如果您只是通过简单的谷歌搜索环顾四周,那么找到最大日期应该很容易做到,这会涉及到一些调整。