Created
February 2, 2017 22:53
-
-
Save aaronice/a1fd6f2b50cb679e874ac30306db8b2c to your computer and use it in GitHub Desktop.
Sort Array Alphabetically and Numerically
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
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 ? 0 : aN > bN ? 1 : -1; | |
} else { | |
return aA > bA ? 1 : -1; | |
} | |
} | |
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum); | |
// Source: http://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment