简体   繁体   中英

Javascript - get 1 oldest date from array of dates

I have an array with this format. I just want to pull the 1 oldest date.

This is value in array looks like:

Array:

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:

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);
            }); 
        }

Expected Result:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM