JS sort () is empty to the end

I have a JS view like this:

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

It works, but some of my notes ""or null.

Empty entries are listed at the beginning, 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?

+10
source share
2 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;
});
+16
source

Shorter way:

['a', '!', 'z','Z', null, undefined, '']
.sort((a, b) => !a ? 1 : (!b ? -1 : (a.localeCompare(b))) )
-1
source

Source: https://habr.com/ru/post/1610765/


All Articles