Reputation: 1668
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.
Upvotes: 3
Views: 70
Reputation:
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>
Upvotes: 2