- 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
Sort Array of numeric & alphabetical elements (Natural Sort) JavaScript
We have an array that contains some numbers and some strings. We are required to sort the array such that the numbers gets sorted and get placed before every string and then the string should be placed sorted alphabetically.
For example −
This array after being sorted
const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
Should look like this −
[1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd']
So, let’s write the code for this −
Example
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);
Output
The output in the console will be −
[ 1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd' ]
Understanding the code −
The main part of this code is the sorter function, we know the callback function receives two arguments, both being the elements of the array.
Now we have four possibilities −
Both a and b are number → in this case we place the smaller number before the bigger
a is number but b is string → in this case we place the number (a) before string (b) as asked in the question.
a is string but b is number → in this case we place b before a
Both a and b are string → we check for the string that is alphabetically smaller i.e., comes before and places it before.
- Related Articles
- Sort Array of numeric & alphabetical elements (Natural Sort) JavaScript
- How to sort mixed numeric/alphanumeric array in JavaScript
- Natural Sort in JavaScript
- Java Program to sort an array in alphabetical order
- How to perform numeric sort in JavaScript?
- Sort subset of array elements in Java
- Using merge sort to recursive sort an array JavaScript
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
- Sort the second array according to the elements of the first array in JavaScript
- C program to sort names in alphabetical order
- Sort the array of strings according to alphabetical order defined by another string in C++
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
- Java Program to sort a subset of array elements
- Sort array by month-year JavaScript
- Sort by index of an array in JavaScript
- How to sort an array elements in android?
