Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

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 datevar da = newDate(a);
    var db = newDate(b);

    // do standard comparison checksif(da < db) {
        return -1;
    } elseif(da > db) {
        return1;
    } else {
        return0;
    }
});

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

Solution 2:

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.

Post a Comment for "Sort Java Script Array Of Formatted Date"