Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 305
phpjssql Avatar asked Oct 08 '15 12:10

phpjssql


1 Answers

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;
});
like image 80
Eric Hotinger Avatar answered Sep 17 '22 17:09

Eric Hotinger