Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Alphanumeric sorting using JavaScript
We have a mixed array that we need to sort by alphabet and then by digit −
const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];
Example
The code for this will be −
const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];
const alphaNumericSort = (arr = []) => {
arr.sort((a, b) => {
const aPart = a.split('-');
const bPart = b.split('-');
return aPart[0].toLowerCase().localeCompare(bPart[0].toLowerCase()) || aPart[1] - bPart[1];
});
};
alphaNumericSort(arr);
console.log(arr);
Output
And the output in the console will be −
[ 'Ab-1', 'ab-2', 'ab-3', 'ab-10', 'Ab-11', 'Ab-12', 'ab-100', 'ab-101', 'ab-105' ]
Advertisements
