Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sort a JavaScript array so the NaN values always end up 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.
Understanding the NaN Property
NaN has a unique characteristic in JavaScript:
console.log(NaN === NaN); // false
console.log(5 === 5); // true
console.log("hello" === "hello"); // true
// Using this property to detect NaN
let value = NaN;
console.log(value !== value); // true (only NaN fails this test)
false true true true
Sorting Algorithm
Our custom sorting function prioritizes values in this order:
- Numbers (excluding NaN) come first
- Strings come second
- NaN values go to the bottom
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);
[ 765, 23, 89, 87, 76, 76, 5, 344, 'fd', '', 'f', 'fdf', 'fgg', NaN, NaN, NaN, NaN ]
How the Sorting Function Works
The comparison function works as follows:
- if(a !== a): Checks if 'a' is NaN. If true, return 1 (move 'a' towards end)
- else if(b !== b): Checks if 'b' is NaN. If true, return -1 (move 'b' towards end)
- return typeof a === 'number' ? -1 : 1: If neither is NaN, prioritize numbers over strings
Alternative Approach Using Number.isNaN()
const arr2 = [344, 'fd', NaN, '', 5, 'f', 76, NaN];
const sorterAlternative = (a, b) => {
if(Number.isNaN(a)) return 1;
if(Number.isNaN(b)) return -1;
return typeof a === 'number' ? -1 : 1;
};
arr2.sort(sorterAlternative);
console.log(arr2);
[ 344, 5, 76, 'fd', '', 'f', NaN, NaN ]
Conclusion
Use the property that NaN !== NaN to detect NaN values in sorting functions. This ensures NaN values are consistently placed at the end while maintaining the desired order for numbers and strings.
