Pushing NaN to last of array using sort() in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We have an array that contains String and number mixed data types, we have to write a sorting function that sorts the array so that the NaN values always end up at the bottom.

The array should contain all the valid numbers in the front, followed by string literals, followed by NaN.

The code for this will be −

const arr = [344, 'gfd', NaN, '', 15, 'f',176, NaN, 736, NaN, 872, 859,
'string', 13, 'new', NaN, 75];
const sorter = (a, b) => {
   if(a !== a){
      return 1;
   }else if(b !== b){
      return -1;
   }
   return typeof a === 'number' ? -1 : 1;
};
arr.sort(sorter);
console.log(arr);

Output

The output in the console −

[
   75, 13, 859,
   872, 736, 176,
   15, 344, 'gfd',
   '', 'f', 'string',
   'new', NaN, NaN,
   NaN, NaN
]
raja
Updated on 14-Oct-2020 07:18:43

Advertisements