Last active
July 6, 2017 14:59
-
-
Save rjloura/521e55de17ebe8f7b2bac9a66247c9d2 to your computer and use it in GitHub Desktop.
Sorting AlphaNumeric Strings in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Straight copy from https://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array */ | |
/* Note that the ^ in [^xyz] creates a negated character set, and does not match the beginning of the line. */ | |
var reA = /[^a-zA-Z]/g; | |
var reN = /[^0-9]/g; | |
function sortAlphaNum(a,b) { | |
var aA = a.replace(reA, ""); | |
var bA = b.replace(reA, ""); | |
if(aA === bA) { | |
var aN = parseInt(a.replace(reN, ""), 10); | |
var bN = parseInt(b.replace(reN, ""), 10); | |
return aN - bN; | |
} else { | |
return aA > bA ? 1 : -1; | |
} | |
} | |
arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]; | |
arr.sort(sortAlphaNum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment