Sort day/month array in Javascript

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

    You'll have to parse the strings into Date() objects, which would be straightforward enough if it weren't for IE's poor implementation of date string parsing. Fortunately, you can use setDate() and setMonth() with consistency across browsers, both accept numbers - 1-31 for setDate(), 0-11 for setMonth(). Setting up an object map for the month names will help.

    This works for me:

    (function () { 
        // Set up our variables, 2 date objects and a map of month names/numbers
        var ad = new Date();
        var bd = new Date();
        var months = {
            Jan: 0,
            Feb: 1,
            Mar: 2,
            Apr: 3,
            May: 4,
            Jun: 5,
            Jul: 6, 
            Aug: 7,
            Sep: 8,
            Oct: 9,
            Nov: 10,
            Dec: 11
        };
    
        MyArray.sort(function (a,b) {
            // Split the text into [ date, month ]
            var as = a.split(' '),
                bs = b.split(' ');
    
            // Set the Date() objects to the dates of the items
            ad.setDate(as[0]);
            ad.setMonth(months[as[1]]);
            bd.setDate(bs[0]);
            bd.setMonth(months[bs[1]]);
    
            /* A math operation converts a Date object to a number, so 
               it's enough to just return date1 - date2 */
            return ad - bd;
        });
    })();
    //-> ["09 Jun", "13 Jun", "30 Jun", "13 Aug", "25 Aug"]
    

    I've set up an example for you - http://jsfiddle.net/Tw6xt/

提交回复
热议问题