
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort JavaScript Array to Place NaN Values at the Bottom
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 normal numbers first followed by string literals and then followed by NaN numbers.
We know that the data type of NaN is “number”, so we can’t check for NaN like !number && !string. Moreover, if we simply check the tautology and falsity of elements then empty strings will also satisfy the same condition which NaN or undefined satisfies.
Check for NaN
So how do we check for NaN. NaN numbers have a special property, and it is that NaN is not equal to NaN, that is for any other value in JS, be it any, the value === value will yield true, but NaN === NaN always yields false. We will use this fact to sort our array.
Example
const arr = [344, 'fd', NaN, '', 5, 'f',76, NaN, 76, NaN, 87, 89, 'fdf', 23, 'fgg', NaN, 765]; 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 will be −
[ 765, 23, 89, 87, 76, 76, 5, 344, 'fd', '', 'f', 'fdf', 'fgg', NaN, NaN, NaN, NaN ]