25

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?

1

3 Answers 3

44

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

care to explain with a diagram ?
I improved this by adding !a || and !b || to the first two conditionals, which accounts for undefined (and short circuits the others as well).
5
records.sort((a,b) => a ? b ? a.localeCompare(b) : -1 : 1);

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

Comments

2

Shorter way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.