3

I have an array that contains values like this:

var testSorting = [0,null,1,0,1,null];

When I sort it like this:

testSorting.sort()

then the output is [0, 0, 1, 1, null, null]

But if I do it like this:

testSorting.sort(function(a, b){
    return a-b;
});
console.log(testSorting);

the output is [0, null, 0, null, 1, 1].

I don't know why the result is like this. I need the result to be like the first method.

1 Answer 1

2

null coerces to 0 in math operations and to a string "null" in .toString() operation, which is what happens when you don't provide a callback.

So in the first code, it's as though you're sorting this:

['0','null','1','0','1','null']

And in the second, it's as though you're sorting this:

[0,0,1,0,1,0];

If you need it to be like the first, then you need to make sure that the a===null values always return a value higher than the other numbers and the b===null values always return one lower.

var testSorting = [0,null,1,0,1,null];

testSorting.sort(function(a, b){
    return a === null ? Infinity :
           b === null ? -Infinity :
                        a - b;
});
document.querySelector("pre").textContent = JSON.stringify(testSorting, 2, null);
<pre></pre>

Sign up to request clarification or add additional context in comments.

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.