Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[].sort ignoring undefined values? [duplicate]

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?

like image 212
Đinh Carabus Avatar asked Nov 09 '22 13:11

Đinh Carabus


1 Answers

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.

like image 193
Gilad Artzi Avatar answered Nov 15 '22 03:11

Gilad Artzi