Q:

Sort java script array of formatted date

I have an javascript array of date which is formatted in a particular way like MM/DD/YYYY.  How can I use  javascript sort function to sort this array? 

A:

You can use Array.sort, but you need to pass a custom comparison function which converts the values to Dates and compares those, instead of just the string value:

var arr = ['07/01/2014', '04/02/2014', '12/11/2013'];

arr.sort(function(a, b) {
    // convert both arguments to a date
    var da = new Date(a);
    var db = new Date(b);

    // do standard comparison checks
    if(da < db) {
        return -1;
    } else if(da > db) {
        return 1;
    } else {
        return 0;
    }
});

// print the result
var result = document.getElementById('result');
for(var i = 0; i < arr.length; ++i)
{
    result.value = result.value + '\n' + arr[i];
}
<textarea id="result" rows="5" cols="50"></textarea>

