

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- Transforming array of numbers to array of alphabets using JavaScript
- Converting numbers into corresponding alphabets and characters using JavaScript
- Indexing numbers to alphabets in JavaScript
- How to separate even and odd numbers in an array by using for loop in C language?
- 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
- Go through an array and sum only numbers JavaScript
- How to pull even numbers from an array in MongoDB?
- Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript
- Difference between numbers and string numbers present in an array in JavaScript
- Returning an array containing last n even numbers from input array in JavaScript
- Reversing alphabets in a string using JavaScript
- Write a Python program to separate a series of alphabets and digits and convert them to a dataframe
- Separate odd and even in JavaScript
Advertisements