小编典典

排序混合的字母/数字数组

javascript

我有一个混合数组,需要按字母然后按数字排序

[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3]

我如何将其排序为:

[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12]

我努力了

arr.sort(function(a,b) {return a - b});

但这只是按字母顺序排序。可以使用直接的JavaScript或jQuery完成此操作吗?


阅读 459

收藏
2020-05-01

共1个答案

小编典典

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)

)
2020-05-01