
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
Natural Sort in JavaScript
We have an array that contains some numbers and some strings, we are required to sort the array such that the numbers get sorted and get placed before every string and then the string should be placed sorted alphabetically.
For example
Let’s say this is our array −
const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
The output should look like this −
[1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd']
Therefore, let’s write the code for this −
const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9]; const sorter = (a, b) => { if(typeof a === 'number' && typeof b === 'number'){ return a - b; }else if(typeof a === 'number' && typeof b !== 'number'){ return -1; }else if(typeof a !== 'number' && typeof b === 'number'){ return 1; }else{ return a > b ? 1 : -1; } } arr.sort(sorter); console.log(arr);
The output in the console will be −
[ 1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd' ]
Advertisements