Vaskar Ray Karmakar
Vaskar Ray Karmakar

Reputation: 101

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?

Upvotes: 0

Views: 123

Answers (2)

Rhumborl
Rhumborl

Reputation: 16609

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>

Upvotes: 3

jwang
jwang

Reputation: 653

Are the dates stored as strings or as Date objects? You can convert each string into a date object by using the Date constructor like new Date('MM/DD/YYYY'). This will give you Date objects and make it much easier to compare. To compare Dates and sort them, just grab their values using the getTime() function to get their value in milliseconds and compare the numbers.

Upvotes: 1

Related Questions