- 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
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' ]
- Related Articles
- Sort Array of numeric & alphabetical elements (Natural Sort) JavaScript
- How do I sort natural in MongoDB?
- Merge sort vs quick sort in Javascript
- Radix sort in Javascript?
- Implementing Priority Sort in JavaScript
- Case-sensitive sort in JavaScript
- Implementing counting sort in JavaScript
- JavaScript Sort() method
- Radix sort - JavaScript
- Sort in multi-dimensional arrays in JavaScript
- Using merge sort to recursive sort an array JavaScript
- How to perform numeric sort in JavaScript?
- Sorting arrays using bubble sort in JavaScript
- Program to implement Bucket Sort in JavaScript
- How to sort date array in JavaScript

Advertisements