Getting unexpected result when sorting with null value in JavaScript

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 exit [0, 0, 1, 1, null, null]

But if I do it like this:

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

      

conclusion [0, null, 0, null, 1, 1]

.

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

+3


source to share


1 answer


null

leads to 0

in math operations and to line "null"

in .toString()

, which happens when you don't provide a callback.

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

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

      

And in the second, as if you were sorting this:



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

      

If you need it to be like the first, you need to make sure that values a===null

always return a value above other numbers, and values b===null

always return one below.

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>
      

Run codeHide result


+2


source







All Articles