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?