1

I have an array like this

["Apr 2014", "Sep 2015", "Jul 2010", "Jun 2016", "Sep 2013"]

I want to sort this array as dates. But when i am using this in date function as new Date("Apr 2014") it shows invalid date format error.

How can i sort this array?

1
  • Without seeing any code, it's difficult to suggest improvements, even if the actual problem is simple. Commented Oct 7, 2016 at 10:13

1 Answer 1

1

You could use a function which separates the date string and returns an array with the year and a month number. The month is taken from an object with month names as hashes.

var array = ["Apr 2014", "Sep 2015", "Jul 2010", "Jun 2016", "Sep 2013", "Jan 2013"];
array.sort(function (a, b) {
    function getMonth(m) {
        return  {
            jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12
        }[m.slice(0, 3).toLowerCase()] || 0;
    }

    var aa = a.split(' '),
        bb = b.split(' ');

    return aa[1] - bb[1] || getMonth(aa[0]) - getMonth(bb[0]);
});
console.log(array);

Sign up to request clarification or add additional context in comments.

Comments