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' ]