Return The Latest Date From Array Of Dates
I have json as follow: 'reviews':[ { 'notes': 'Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!',
Solution 1:
As per the docs, If at least one of arguments cannot be converted to a
number
, the result isNaN
Andnew Date(NaN)
will beInvalid Date
Wrap the date string in new Date
while pushing in array. When DateObject
is passed through Number
, numeric value representing date
will be returned.
var data = {
"reviews": [{
"notes": "Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!",
"date": "2015-04-18",
"rating": {
"overall": 100
}
}, {
"notes": "I messed up the days I was supposed to be there but they did everything they could to get me a room, which I did. The guy at the front was super nice and then drew me an entire map based off of how much time I had there in Rome. It was extremely helpful and the restaurant he recommends (a friends who you get 10% off of) had good lasagna. Great place for a really reasonable price. Also, the doors do not automatically lock for you room, so just remember to lock your door when you leave. ",
"date": "2016-04-18",
"rating": {
"overall": 94
}
}]
};
functionhighestReview() {
var maxNumb = [];
for (var y = 0; y < data.reviews.length; y++) {
maxNumb.push(newDate(data.reviews[y].date));
}
var latestDate = newDate(Math.max.apply(null, maxNumb));
console.log(latestDate);
}
highestReview();
Solution 2:
You could use Array#reduce
and compare the date as string, while it is an ISO date.
var data = { "reviews": [{ "notes": "Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!", "date": "2015-04-18", "rating": { "overall": 100 } }, { "notes": "I messed up the days I was supposed to be there but they did everything they could to get me a room, which I did. The guy at the front was super nice and then drew me an entire map based off of how much time I had there in Rome. It was extremely helpful and the restaurant he recommends (a friends who you get 10% off of) had good lasagna. Great place for a really reasonable price. Also, the doors do not automatically lock for you room, so just remember to lock your door when you leave. ", "date": "2016-04-18", "rating": { "overall": 94 } }] },
latestDate = data.reviews.reduce(function (r, a, i) {
return !i || a.date > r ? a.date : r;
}, undefined);
document.write('<pre>' + JSON.stringify(latestDate, 0, 4) + '</pre>');
Solution 3:
You must convert your date values to Date objects first:
functionhighestReview() {
var maxNumb = [];
for(var y = 0; y < data.reviews.length; y++){
maxNumb.push(newDate(data.reviews[y].date));
}
var latestDate = newDate(Math.max.apply(null, maxNumb));
console.log(latestDate);
}
highestReview();
Hope it helps
Post a Comment for "Return The Latest Date From Array Of Dates"