By looking at the js sort
documentation you'll see that sort is taking a function as parameter which :
- Return a positive integer if the first object is bigger than the second one
- Return 0 if the two objects are the same
- Return a negative integer if the first object is smaller than the second one.
Knowing that, let's build the function together :
First, we'd like to get the highest date for on object.
For that, i would recommend using Math.max which takes an array and returns the biggest parameters.
Here it works because js understand date as integers.
function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}
Now let's build the sort function.
function compare(a,b){
return highestDate(b) - highestDate(a)
}
here is a snipper for testing :
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))