[Javascript] Sorting Problem

liorean liorean at gmail.com
Tue Sep 14 11:23:45 CDT 2004


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/>



More information about the Javascript mailing list