PDA

View Full Version : Sorting an array of dates

rob446
05-17-2004, 06:58 PM
Hi folks,

If anyone can point me in the direction of a way to sort an array of dates, I would be most grateful.

e.g. array containing 19/06/2004,15/05/2004,17/05/2004,08/05/2003 sorted to result in 08/05/2003,15/05/2004,17/05/2004,19/06/2004

Thank you

pixelwit
05-17-2004, 07:39 PM
myDates = ["19/06/2004", "15/05/2004", "17/05/2004", "08/05/2003"];
function dateSort(d1, d2){
d1 = d1.split("/");
d2 = d2.split("/");
if(d1[2]>d2[2]){
return 1
}else if(d1[2]<d2[2]){
return -1;
}else{
if(d1[1]>d2[1]){
return 1;
}else if(d1[1]<d2[1]){
return -1;
}else{
if(d1[0]>d2[0]){
return 1;
}else if(d1[0]<d2[0]){
return -1;
}
}
}
}
trace(myDates);
myDates.sort(dateSort);
trace(myDates);

-PiXELWiT
http://www.pixelwit.com

ericlin
05-17-2004, 08:32 PM
I have another option. However, this is less efficient than the code pixelwit post.

If the date format is always in the form of dd/mm/yyyy, then we can re-arrange them as yyyy/mm/dd. Then do the comparison.

rob446
05-18-2004, 03:40 AM
Thank you very much PiXELWiT. I was thinking along those lines myself , but couldn't quite get my head around the function for array.sort.

ericlin
05-18-2004, 04:07 AM
myDates = ["19/06/2004", "15/05/2004", "17/05/2004", "08/05/2003"];
function dateSort(d1, d2) {
d1 = d1.split("/").reverse().join();
d2 = d2.split("/").reverse().join();
return (d1>d2) ? 1 : -1;
}
trace(myDates);
myDates.sort(dateSort);
trace(myDates);

pixelwit
05-18-2004, 04:29 PM
You're welcome Rob446.

That's pretty sweet Ericlin, I like it. I thought your way might run a little quicker than mine because all my comparisons use array notation but it turns out that you're right again. My way takes about 80% of the time it takes to run your code. Thanks for your alternative point of view.

-PiXELWiT
http://www.pixelwit.com

ericlin
05-18-2004, 07:08 PM
:) Yea, I think Array.reverse and Array.join are slow.

BTW, it seems that you could remove all the "else" in your code.

pixelwit
05-18-2004, 07:35 PM
True, the code could be written as:function dateSort2(d1, d2) {
d1 = d1.split("/");
d2 = d2.split("/");
if (d1[2]>d2[2]) return 1;
if (d1[2]<d2[2]) return -1;
if (d1[1]>d2[1]) return 1;
if (d1[1]<d2[1]) return -1;
if (d1[0]>d2[0]) return 1;
if (d1[0]<d2[0]) return -1;
}
But I like the seeing the structure of the code in the first example plus it's a little easier to insert a line if you want to make modifications later. Mostly I do it just because it's a habit I guess, but from what I can tell neither one runs any faster than the other.

Thanks for keeping me on my toes. ;)

-PiXELWiT
http://www.pixelwit.com