When comparing two objects a
and b
, it is necessary to ensure that one of them is not null
.
However, deciphering this can be quite chaotic.
{} - null => -0
[] - null => 0
1 - null => 1
"1" - null => 1
true - null => 1
false - null => 0
"a" - null => NaN
null - null => 0
"a" == null false
"a" > null false
"a" < null false
let arr = [
{ name: "a" },
{ name: null },
null,
{ name: "zaa" },
{ name: "dgh" }
];
let sortByName = function (a, b) {
if (a == null || b == null) return a - b;
if (a.name == null || b.name == null) return a.name - b.name;
return a.name.localeCompare(b.name);
};
console.log(arr.sort(sortByName));
The resulting order is as follows:
0: {name: 'a'}
1: {name: null}
2: null
3: {name: 'dgh'}
4: {name: 'zaa'}
Can you provide an explanation for this outcome?