23

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?

VisioN
  • 143,310
  • 32
  • 282
  • 281
phpjssql
  • 471
  • 1
  • 4
  • 16

3 Answers3

39

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;
});
Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
3
records.sort((a,b) => a ? b ? a.localeCompare(b) : -1 : 1);

A ES6 one-liner version of Eric Hotinger's answer

Joey Carlisle
  • 586
  • 4
  • 12
2

Shorter way:

['a', '!', 'z','Z', null, undefined, '']
.sort((a, b) => !a ? 1 : (!b ? -1 : (a.localeCompare(b))) )
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84