I've got some json that returns a number of dates like this:
{
"items": [{
"metafield1": "May 22 2019"
}, {
"metafield1": null
}, {
"metafield1": null
}, {
"metafield1": "May 20 2019"
}]
}
I've then got an ajax call which gets the data and loops through it to check if it doesn't equal null
success: function(result) {
var obj = JSON.parse(result);
obj = obj["items"];
for(var i of obj){
if(i.metafield1 !== null){
console.log(i.metafield1);
}
}
This returns something like this
May 22 2019
May 20 2019
I now need to compare these dates and find the highest (the one the furthest into the future). I know I can do the date comparison with the Date object like
var date1 = May 22 2019
var date2 = May 20 2019
var newdate1 = new Date(date1)
var newdate2 = new Date(date2)
if (newdate1 > newdate2){
var biggest_date = newdate1
}
else {
var biggest_date = newdate2
}
Or something like this. My issue is how do I assign those within my loop and make it work if it's more than two items in the loop. So let's say my loop returns this
May 22 2019
May 20 2019
July 20 2019
How can I get and compare those three values (which are dynamic, so it varies how many of them there are) to find the biggest date?