0

I have an array which contains these values

daterangefordb = [ "12/16/2015", "11/25/2015", "01/06/2016", "12/30/2015" ]

When I sort I get this using daterangefordb.sort():

[ "01/06/2016", "11/25/2015", "12/16/2015", "12/30/2015" ]

Whereas, expected sort values should be -

[ "11/25/2015", "12/16/2015", "12/30/2015", "01/06/2016" ]

Any solutions?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Anil Purswani
  • 1,857
  • 6
  • 35
  • 63

2 Answers2

2

The sort() method with no function provided to it will perform a simple alphanumeric sort on the values of the array as strings. In your case you need to convert them to dates before comparing. Try this:

var sorted = daterangefordb.sort(function(a, b) {
    var aDate = new Date(a);
    var bDate = new Date(b);
    if (aDate < bDate)
        return -1;
    else if (aDate > bDate)
        return 1;
    return 0;
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

These are strings, therefore properly sorted . If you wish to sort them as daes, then convert them to dates

new Date( "11-05-2015".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

Something like this works

Elentriel
  • 1,237
  • 8
  • 21