How do you sort a JavaScript array that includes NaNs?

arrays, javascript, nan, sorting

Solution

Note: this solution has problems with some edge-cases and seems to be not fully browser independent, please refer to the answer by Esailija or the modern one from trincot

You can catch `NaN` and `Infinity` using JavaScript's built-in utility functions for those cases:

//sort -Infinity, NaN, Infinity to the end in random order
func = 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(...[Infinity, -1, 6, 1, 0, NaN, 0, -1, 2, 5, 10, -Infinity, NaN, Infinity, NaN].sort(func))
// fails for edge case
console.log(...[-Number.MAX_VALUE, Number.MAX_VALUE].sort(func))
console.log(...[Number.MAX_VALUE, -Number.MAX_VALUE].sort(func))




//sort -Infinity<0<Infinity<NaN
func = function(a,b){
  if(isNaN(a)) { 
    return isNaN(b) ? 1 : b;
  } else {
    return isNaN(b) ? -1 : a-b; 
  }
}

//[-Infinity,-1,-1,0,0,1,2,5,6,10,Infinity,Infinity,NaN,NaN,NaN]
console.log(...[Infinity, -1, 6, 1, 0, NaN, 0, -1, 2, 5, 10, -Infinity, NaN, Infinity, NaN].sort(func))
console.log(...[-Number.MAX_VALUE, Number.MAX_VALUE].sort(func))
console.log(...[Number.MAX_VALUE, -Number.MAX_VALUE].sort(func))

Problem

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 ```

Original source