I have an array of strings in JS that represent dates on the format M/D/Y where M and D can have one or two digits each. How can I write a callback function do sort this array?
2 Answers
Date.parse() (to which new Date(string) is equivalent) is not consistent across JS implementations, so I should probably manually parse the date strings first for consistency, then do exactly as Minko Gechev suggests:
array.sort(function (d1, d2) {
function parseDate(str) {
var parts = str.match(/(\d+)/g);
// assumes M/D/Y date format
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
return parseDate(d1) - parseDate(d2);
});
As an aside, I'd argue you're almost always better off storing Date objects rather than strings, and then formatting your Dates as strings as and when you need them for output anyway, as it makes this sort of manipulation easier, and makes your code clearer too.
1 Comment
EBM
I agree, but the source dates weren't stored by me.