Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How do you sort an array that includes NaN's

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
like image 398
techdog Avatar asked Jul 09 '13 20:07

techdog


2 Answers

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

like image 168
Esailija Avatar answered Oct 24 '22 23:10

Esailija


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);
like image 39
Fabian N. Avatar answered Oct 24 '22 23:10

Fabian N.