How Sort Array Date JavaScript dd/mm/yyyy?

前端 未结 5 1867
梦毁少年i
梦毁少年i 2020-12-10 08:17

How would I sort an array of dates in chronological order? For example I have:

var dates = [
    \'03/03/2014\',
             


        
5条回答
  •  误落风尘
    2020-12-10 08:40

    Try this (feel free to ask for details) :

    dates.sort(function (a, b) {
        // '01/03/2014'.split('/')
        // gives ["01", "03", "2014"]
        a = a.split('/');
        b = b.split('/');
        return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
    });
    

    Translation of the last line :

    return          return
    a[2] - b[2]     years comparison if year A - year B is not 0
    ||              or
    a[1] - b[1]     months comparison if month A - month B is not 0
    ||              or
    a[0] - b[0];    days comparison
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

提交回复
热议问题