- 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
How to sort mixed numeric/alphanumeric array in JavaScript
Suppose we have an array of alphanumeric strings like this −
const arr = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3'];
We are required to write a JavaScript function that in one such array as one and the only argument.
And the function should sort this array inplace −
- The strings that contains only numbers should come first sorted in increasing order.
- The strings containing a combination of alphabets and numbers should be sorted first according to alphabets and then according to numbers in increasing order.
Therefore, the output should look like −
const output = ['1', '2', 'A1', 'A2', 'A3', 'A3A', 'A3B', 'A4', 'A10', 'A11', 'A12', 'B2', 'B10', 'F1', 'F3'];
Example
const arr = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3']; const alphaNumericSort = (arr = []) => { const sorter = (a, b) => { const isNumber = (v) => (+v).toString() === v; const aPart = a.match(/\d+|\D+/g); const bPart = b.match(/\d+|\D+/g); let i = 0; let len = Math.min(aPart.length, bPart.length); while (i < len && aPart[i] === bPart[i]) { i++; }; if (i === len) { return aPart.length - bPart.length; }; if (isNumber(aPart[i]) && isNumber(bPart[i])) { return aPart[i] - bPart[i]; }; return aPart[i].localeCompare(bPart[i]); }; arr.sort(sorter); }; alphaNumericSort(arr); console.log(arr);
Output
And the output in the console will be −
[ '1', '2', 'A1', 'A3', 'A3A', 'A3B', 'A4', 'A10', 'A11', 'A12', 'B2', 'B10', 'F1', 'F3' ]
- Related Articles
- Sort Array of numeric & alphabetical elements (Natural Sort) JavaScript
- How to perform numeric sort in JavaScript?
- How to do alphanumeric sort in MongoDB?
- How to sort an alphanumeric column in MySQL?
- Sort strings in Alphanumeric sequence
- How to sort date array in JavaScript
- How to sort an alphanumeric column with different lengths in MySQL?
- Alphanumeric Order by in MySQL for strings mixed with numbers
- How to sort array according to age in JavaScript?
- Sort only numbers from alphanumeric string in MySQL?
- Sort an array according to another array in JavaScript
- How to sort an array in JavaScript?Explain with example?
- How to sort an array of integers correctly in JavaScript?
- How to sort array by first item in subarray - JavaScript?
- Fill missing numeric values in a JavaScript array

Advertisements