Sort day/month array in Javascript

前端 未结 4 1195
南方客
南方客 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:36

    You would have to pass a sorting function to the sort method and define a date parsing function that creates an ordered representation of the date like so:

    var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"];
    MyArray.sort(function (a, b) {
        a = parseDate(a);
        b = parseDate(b);
        if (a < b) {
                return 1;
        } else if (a > b) {
                return -1;
        } else {
                return 0;
        }
    });
    

提交回复
热议问题