Sort day/month array in Javascript

前端 未结 4 1184
南方客
南方客 2021-01-23 12:10

I\'m trying to sort an Array of dates from latest to oldest, and unfortunately list.sort (by default) only sorts the first number. My array looks like this:

var          


        
4条回答
  •  不要未来只要你来
    2021-01-23 12:35

    You can pass a function to sort to do custom sorting:

    function sortDate (a,b) {
        var aa = a.split(' ');
        var bb = b.split(' ');
        var months = {
            Jan : 1,
            Feb : 2,
            Mar : 3 /* you do the rest ... */
        }
    
        if (months[a[1]] > months[b[1]]) return 1;
        if (months[a[1]] < months[b[1]]) return -1;
    
        return parseInt(a[0],10) - parseInt(b[0],10);
    }
    
    MyArray.sort(sortDate);
    

提交回复
热议问题