I have an array with this format. I just want to pull the 1 oldest date.
This is value in array looks like:
creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21:31:04 GMT 2019'];
This is my code:
// this below code is not working as expected
if(creationDate){
var orderedDates = creationDate.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
}
Wed Feb 13 21:14:55 GMT 2019
You can use Array.reduce()
and on each iteration compare the dates and take the oldest:
const creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21:31:04 GMT 2019']; const oldest = creationDate.reduce((c, n) => Date.parse(n) < Date.parse(c) ? n : c ); console.log(oldest);
You want to return a number, not a Boolean (so use -
not >
):
var creationDate = ['Wed Feb 13 21:14:55 GMT 2019', 'Wed Feb 13 21:19:42 GMT 2019', 'Wed Feb 13 21:28:29 GMT 2019', 'Wed Feb 13 21:31:04 GMT 2019', 'Wed Feb 13 21:33:04 GMT 2019']; var orderedDates = creationDate.sort(function(a, b) { return Date.parse(a) - Date.parse(b); }); console.log(orderedDates[0]);
Try:
if(creationDates){
return creationDates.sort()[0]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.