user1371896
user1371896

Reputation: 2230

sorting an array based on time in javascript

I have an array in the format

["09-02-2010", " 05-08-2010", "11-11-2010",  "27-09-2010", "10-12-2010", "09-09-2010", "03-09-2010", "13-08-2010", , "11-10-2010","09-06-2010", "08-06-2010", "07-06-2010" ]

I am trying to sort the array based on the decreasing order of dates..

     dateArray.sort( mdyOrdD);

     var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;

      function mdyOrdD(a, b){
       a = a.replace(dateRE,"$3$1$2");
       b = b.replace(dateRE,"$3$1$2");
       if (a>b) return -1;
       if (a <b) return 1;
       return 0; }

bt this didnt work our completely.. What could be wrong and is there any other good way to solve this??

Upvotes: 3

Views: 235

Answers (1)

Bergi
Bergi

Reputation: 664579

Since your dates are in DD-MM-YYYY format and you want them to be YYYYMMDD to sort alphabetically, use

   a = a.replace(dateRE,"$3$2$1");
   b = b.replace(dateRE,"$3$2$1");

instead.

Upvotes: 1

Related Questions