Reputation: 153
So I have an array of dates in the the format in the title, for example:
const dates = ["2014-13-01T13:81:00.862279Z", "2009-10-04T11:21:00.8322170Z", ...];
Whats the best/ correct way to get the earliest and latest date?
I can see theres obvious, yet unduly long ways to sort on each segment of each date, but I was wondering if there was an inbuilt date function in JavaScript which could do this natively.
I don't wish to import any libraries, such as Moment.js.
Upvotes: 3
Views: 289
Reputation: 386730
You could reduce the array and use a string comparison for getting the smallest or greatest ISO 8601 in a single loop.
[earliest, latest] = arrayOfISOStrings.reduce((r, iso, i) => {
if (!i) return [iso, iso];
if (iso < r[0]) r[0] = iso;
if (iso > r[1]) r[1] = iso;
return r;
}, []);
Upvotes: 2
Reputation: 87
Since you are sorting string and your format goes from the Year month day, Hour minutes seconds, you can use the built in sort function. However if the format is different then this won't be the best choice
dates.sort()
const dates = ["2014-13-01T13:81:00.862279Z", "2009-10-04T11:21:00.8322170Z", "2009-10-05T11:21:00.8322170Z", "2009-10-04T11:21:00.8422170Z"];
console.log(dates.sort());
Upvotes: 3