
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
Separate Alphabets and Numbers from an Array using JavaScript
We have an array that contains some number literals and some string literals mixed, and we are required to write a sorting function that separates the two and the two types should also be sorted within.
The code for this sorting function will be −
Example
const arr = [1, 5, 'fd', 6, 'as', 'a', 'cx', 43, 's', 51, 7]; const sorter = (a, b) => { const first = typeof a === 'number'; const second = typeof b === 'number'; if(first && second){ return a - b; }else if(first && !second){ return -1; }else if(!first && second){ return 1; }else{ return a > b ? 1 : -1; } }; arr.sort(sorter); console.log(arr);
Output
The output in the console will be −
[ 1, 5, 6, 7, 43, 51, 'a', 'as', 'cx', 'fd', 's' ]
Advertisements