There are quite a few question related to the topic, but I couldn't find the right solution for my case.
var arr = [a, b, null, d, null]
and am sorting this Array with below logic
return function(a,b){
if(a === null){
return 1;
}
else if(b === null){
return -1;
}
else if(a === b){
return 0;
}
else if(ascending) {
return a < b ? -1 : 1;
}
else if(!ascending) {
return a < b ? 1 : -1;
}
};
I get the following outputs for
Ascending : [a, b, d, null,null]
Descending : [d, b, a, null,null]
Expected : [null, null,d, b, a]
What am I doing wrong?
nulldoes not rely onascendingvariable value. PS: it's ugly and confusing when a comparison function is not pure.