JavaScript: How do you sort an array that includes NaN's
If you just want to bump them to the end in a random order:
var arr = [-1, 0, 1, 10, NaN, 2, NaN, 0, -1, NaN, 5, Infinity, 0, -Infinity];
arr.sort(function(a,b){
if( !isFinite(a) && !isFinite(b) ) {
return 0;
}
if( !isFinite(a) ) {
return 1;
}
if( !isFinite(b) ) {
return -1;
}
return a-b;
});
//[-1, -1, 0, 0, 0, 1, 2, 5, 10, NaN, NaN, NaN, Infinity, -Infinity]
If you want to also sort the infinities at the end:
var arr = [-1, 0, 1, 10, NaN, 2, NaN, 0, -1, NaN, 5, Infinity, 0, -Infinity];
arr.sort(function(a,b){
if( !isFinite(a) && !isFinite(b) ) {
return ( isNaN(a) && isNaN(b) )
? 1
: a < b
? -1
: a === b
? 0
: 1;
}
if( !isFinite(a) ) {
return 1;
}
if( !isFinite(b) ) {
return -1;
}
return a-b;
});
//[-1, -1, 0, 0, 0, 1, 2, 5, 10, -Infinity, Infinity, NaN, NaN, NaN]
Here the order is -Infinity
< Infinity
< NaN
You can catch NaN
and Infinity
using JavaScript's built-in utility functions for those cases:
let array = [Infinity, -1, 6, 1, 0, NaN, 0, -1, 2, 5, 10, -Infinity, NaN, Infinity, NaN]
//sort -Infinity, NaN, Infinity to the end in random order
array.sort(function(a,b){
if(isFinite(a-b)) {
return a-b;
} else {
return isFinite(a) ? -1 : 1;
}
});
//[-1,-1,0,0,1,2,5,6,10,NaN,Infinity,Infinity,NaN,-Infinity,NaN]
console.log(array);
//sort -Infinity<0<Infinity<NaN
array.sort(function(a,b){
if(isNaN(a)) {
return 1-isNaN(b);
} else {
return a-b;
}
});
//[-Infinity,-1,-1,0,0,1,2,5,6,10,Infinity,Infinity,NaN,NaN,NaN]
console.log(array);
Negative infinity should logically be ordered first, as it is effectively smaller than all other numbers.
I would thus do it like this:
const cmp = (a,b) => a-b || isNaN(a)-isNaN(b);
// Example
const arr = [Infinity, NaN, Infinity, -Infinity, NaN, 1, 0, NaN, -1, -0];
console.log(arr.sort(cmp));