I want to sort an array containing undefined/null and numbers, so that undefined/null values always come first:
function sorter(a, b) {
if (a == b) return 0;
if (a == undefined) return -1;
if (b == undefined) return 1;
return a - b;
}
However, when the array contains an undefined value it becomes the last element
[-1, 0, 1, undefined, 2, 3].sort(sorter); // [-1, 0, 1, 2, 3, undefined]
while it gets sorted correctly if the value is null
[-1, 0, 1, null, 2, 3].sort(sorter); // [null, -1, 0, 1, 2, 3]
What am I doing wrong? Shouldn't this result in exactly the same order since null == undefined?
If you add console.log(a, b)
to your sorter
function, you'll see that the undefined
value is never passed into the sorter
function. I think that the interpreter thinks the it's a "gap" in the array and thus don't really consider it as a value.
And by the way, null == undefined
is true
, but null === undefined
is false, they are not the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With