- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pushing NaN to last of array using sort() in JavaScript
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 ]
Advertisements