I'm trying to sort an array that sometimes has Infinity
or NaN
. When I use a standard JavaScript array.sort()
it seems to sort until it reaches a NaN
and then I get random results after that.
var array =[.02,.2,-.2,Nan,Infinity,20];
Is there a way to still sort this so that the end result is from negative to positive and still have NaN
or Infinity
at the end.
-.2,.02,.2,20,NaN,Infinity
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With