- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to 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' ]
- Related Articles
- Transforming array of numbers to array of alphabets using JavaScript
- Converting numbers into corresponding alphabets and characters using JavaScript
- How to separate even and odd numbers in an array by using for loop in C language?
- Indexing numbers to alphabets in JavaScript
- How do you separate zeros from non-zeros in an integer array using Java?
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Finding even length numbers from an array in JavaScript
- How to filter values from an array using the comparator function in JavaScript?
- How to pull even numbers from an array in MongoDB?
- Returning an array containing last n even numbers from input array in JavaScript
- Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript
- Using recursion to remove consecutive duplicate entries from an array - JavaScript
- How to read data from JSON array using JavaScript?
- Go through an array and sum only numbers JavaScript
- JavaScript - How to pick random elements from an array?

Advertisements