排序numAlpha字符串列表

时间:2016-06-12 16:44:41

标签: javascript sorting

我试图对包含数字和字符串的字符串列表进行排序。 alpha序列。我想首先按数字排序,然后按alpha,例如1a,2b,4,77c,743等进行排序。

我一直在玩下面的javascript,而且我已经接近撞墙了。谁能给我一些指示?

var a1 = ["4a", "4c", "1a", "4b", "13c", "4a", "1a", "11c", "112c", "12", "9"];

var a2 = a1.sort(function(a, b) {

  if (a.slice(-1) == "a" || a.slice(-1) == "b" || a.slice(-1) == "c") {
    var charPart = [a.slice(-1), b],
      numPart = [a.slice(0, a.length - 1), b];
    if (b.slice(-1) == "a" || b.slice(-1) == "b" || b.slice(-1) == "a") {
      var charPart = [a.slice(-1), b.slice(-1)],
        numPart = [a.slice(0, a.length - 1), b.slice(0, b.length - 1)];
    }
  }


  if (numPart[0] < numPart[1]) return -1;
  else if (numPart[0] > numPart[1]) return 1;
  else if (numPart[0] == numPart[1]) return -1;
  else {
    if (charPart[0] < charPart[1]) return -1;
    else if (charPart[0] > charPart[1]) return 1
  }
});

http://jsfiddle.net/8fRsD/307/

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式将字符串与前瞻分割为非数字值。

例如'13c'在分割['13', 'c']之后变为现实。

在回调中,值或默认值(如空字符串)用于比较。

&#13;
&#13;
var a1 = ["4a", "4c", "1a", "4b", "13c", "4a", "1a", "11c", "112c", "12", "9"];
		
a1.sort(function (a, b) {
    var aa = a.split(/(?=\D)/),
        bb = b.split(/(?=\D)/);
    return aa[0] - bb[0] || (aa[1] || '').localeCompare(bb[1] || '');
});
console.log(a1);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果目标是首先按每个字符串中的(第一个)数字部分进行排序,然后在具有相同数值的条目中按字符串的(第一个)alpha部分进行排序,则执行此操作 - 请参阅注释:

var a1 = ["4a", "4c", "1a", "4b", "13c", "4a", "1a", "11c", "112c", "12", "9"];
a1.sort(function(l, r) {
  var lnum = l.match(/\d+/);
  var rnum = r.match(/\d+/);
  if (lnum && rnum) {
    // We have numbers, compare them
    lnum = +lnum[0];
    rnum = +rnum[0];
    if (lnum != rnum) {
      // Not the same, put the smaller one first
      return lnum - rnum;
    }
  }
  
  // Either no numbers, or they match; use alpha
  var lalpha = l.match(/\D+/);
  var ralpha = r.match(/\D+/);
  if (lalpha && ralpha) {
    // We have alpha, return result of comparing them
    return lalpha[0].localeCompare(ralpha[0]);
  }
  
  // Neither numbers or alpha; give up
  return 0;
});
console.log(a1);