phpjssql phpjssql - 6 months ago 9
Javascript Question

JS sort() empty to end

I have a JS sort like this:

records.sort(function(a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});


This works, but some of my records are
""
or
null
.

The empty records are listed at the begin but I want them at the end.

I think there are better ways to do this than:

if (a == "") a = "zzzz";


But how can I do this?

eh. eh.
Answer

Maybe something like this:

records.sort(function(a, b) {
    if(a === "" || a === null) return 1;
    if(b === "" || b === null) return -1;
    if(a === b) return 0;
    return a < b ? -1 : 1;
});