-
互换的青春
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; }}console.log(["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum))
-
HUWWW
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`用法:const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))给出:["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]您可能必须将'en'参数更改为您的语言环境或以编程方式确定,但这适用于英语字符串。同样localeCompare也不受超级一致的支持,但是如果您使用babel进行转译不会有问题
-
Qyouu
我也遇到类似的情况,但是混合使用字母数字和数字,因此需要先对所有数字进行排序,然后再对字母数字进行排序,因此:A1015A92B3A2需要成为:125A2A9A10B3我能够使用提供的算法并对它进行更多修改以实现此目的:var reA = /[^a-zA-Z]/g;var reN = /[^0-9]/g;function sortAlphaNum(a,b) { var AInt = parseInt(a, 10); var BInt = parseInt(b, 10); if(isNaN(AInt) && isNaN(BInt)){ 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; } }else if(isNaN(AInt)){//A is not an Int return 1;//to make alphanumeric sort first return -1 here }else if(isNaN(BInt)){//B is not an Int return -1;//to make alphanumeric sort first return 1 here }else{ return AInt > BInt ? 1 : -1; }}var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);