[Javascript] Sorting Problem

Tim Makins spindrift at oceanfree.net
Tue Sep 14 12:39:51 CDT 2004


Well, that's a start. Its not crashing now, but the numerical search results
aren't quite right either:

0.129872
0.164749
0
10.1961
10.5643
1003
100
104.813049
10
11.390914
1121

function numeric_sort(a, b) {
 return (isNaN(a)&&isNaN(b))? alpha_sort(a,b): numSort(a,b);
}

function alpha_sort(a, b) {
 if (a < b) {return -1}
 else if (a > b) {return 1}
 else {return 0}
}

function numSort(a,b){
 return
(isNaN(a)?Number.POSITIVE_INFINITY:a)-(isNaN(b)?Number.POSITIVE_INFINITY:b)
}


----- Original Message ----- 
From: "liorean" <liorean at gmail.com>
To: "[JavaScript List]" <javascript at latech.edu>
Sent: Tuesday, September 14, 2004 5:23 PM
Subject: Re: [Javascript] Sorting Problem


> On Tue, 14 Sep 2004 17:56:58 +0200, Hakan M (Backbase)
> <hakan at backbase.com> wrote:
> > By the way,
> >     element1 - element2;
> > isn't really doing much, since the result is not assigned anywhere. ;)
>
> Au contraire, it is essential for it to work. The Array.prototype.sort
> method will run this function on two elements and sort them depending
> on the returned value. It works the same as the -1:0:1 return values
> the alpha sort uses.
>
> As for fixing it, try doing like this, if you want to sort numericals
> above and non-numericals below:
>
> function numSort(a,b){
>     return
(isNaN(a)?Number.POSITIVE_INFINITY:a)-(isNaN(b)?Number.POSITIVE_INFINITY:b)
> }
>
> If you want to sort the numbers and numerical strings numerically but
> the non-numerical strings alphabetically, try this:
>
> function numAlphaSort(a,b){
>     return (isNaN(a)&&isNaN(b))?
>         alphaSort(a,b);
>         numSort(a,b);
> ]
> -- 
> David "liorean" Andersson
> <uri:http://liorean.web-graphics.com/>
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
>




More information about the Javascript mailing list