Michael Hill wrote:
[color=blue]
> I have this large array with dates in it. There is a function that sorts it
> for me. The only problem is that in order for it to get sorted properly I
> have to sort it AlphaNumerically first using
>
> this first:
>
> list_b_array = cf_array.sort(function(a,b){return
> compareAlpha(a[0],b[0]);});
>
> then this:
>
> list_array = list_b_array.sort(function(a,b){return
> compareDate(a[0],b[0]);});
>
> to get the values in list_array properly sorted. Anyone see anything wrong
> with the compareDate() function?
>
> The array is much larger. I've just shown how the date is formatted and that
> null values exist.
>
> var cf_array = [ "","11/10/2003","11/28/2004","" ];
>
> function compareDate(a,b)
> {
> var date_a = new Date(a);
> var date_b = new Date(b);
> if (date_a < date_b) { return -1; }
> else
> {
> if (date_a > date_b) { return 1; }
> else
> { return 0; }
> }
>
> function compareAlpha(a,b)
> {
> //compare alpha charadcters
> if ( a.toLowerCase() < b.toLowerCase() ) { return -1; }
> if ( a.toLowerCase() > b.toLowerCase() ) { return 1; }
> return 0;
> }[/color]
It's not the compareDate function that's at fault. It's the fact that you're
trying to pass the first array element of the dates (a[0] and b[0]) to
compareDate, when in fact you just want to pass the dates themselves.
var cf_array = [ "","11/28/2004","","11/10/2003","","","12/01/2004","" ];
alert(cf_array.sort(compareDate))
function compareDate(a,b) {
var date_a = new Date(a);
var date_b = new Date(b);
if (!isNaN(date_a) && !isNaN(date_b)) {
return (date_a - date_b);
} else if (isNaN(date_a)) {
return -1;
} else if (isNaN(date_b)) {
return 1;
}
}
You need to deal with the isNaN() issues because new Date("") returns NaN. If
neither the first date nor the second date are NaN, then you just return the
difference (this returns a negative number when date_a is greater then date_b,
positive number when date_a is less then date_b and zero when they are the
same). Otherwise if the first date is NaN, sort it to the top, if the second
date is NaN sort it to the bottom.
--
| Grant Wagner <gwagner@agricoreunited.com>
* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html
* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp
* Netscape 6/7 DOM Reference available at:
*
http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
*
http://www.mozilla.org/docs/web-deve...upgrade_2.html