简体   繁体   中英

Min/Max of dates in an array

 var expenseDates = ["2018-02-06","2018-11-08","2018-11-10","2017-05-02","2017-05-02","2018-11-01"]; var sorted = expenseDates.slice() .sort(function(a, b) { return new Date(a) - new Date(b); }); console.log(sorted.pop()+ '--max'); console.log(sorted.shift()+ '--min'); 

You don't have convert it into date object as the date are in YYYY-MM-DD format which itself is in sorted order by year => month => day . So you just have to compare the input string as localCompare . First index is minimum date while the last index is maximum date

var expenseDates = ["2018-02-06","2018-11-08","2018-11-10","2017-05-02","2017-05-02","2018-11-01"];

    expenseDates = expenseDates.sort(function(a, b) {
        return a.localeCompare(b);
    });

   console.log('--min => ',expenseDates[0]);
   console.log('--max => ', expenseDates[expenseDates.length -1]);

Working jsFiddle demo - https://jsfiddle.net/rpdon5cm/1/

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