Reputation: 1099
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?
Upvotes: 0
Views: 1499
Reputation: 104810
You can also split the strings into their m d y components and compare the components.
array.sort(function(a,b){
var a1= a.split('/'), b1=b.split('/');
if(a1[2]==b1[2]){
return (a1[0]==b1[0])? a1[1]-b1[1]: a1[0]-b1[0];
}
return a1[2]-b1[2];
}
Upvotes: 1
Reputation: 1890
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.
Upvotes: 3