JavaScript localeCompare排序不好[" aaa-1.0"," aaa-1.1"," aaa-1.01"," AAA-11"" AAA-2.01"]

时间:2017-10-20 11:02:52

标签: javascript sorting

我想按照"十进制"来排序字符串。数字值以及字母顺序。保持它的自然顺序。

var strArray = ["aaa-0", "aaa-0.01", "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-2.01", "bbb-2.01", "aaa-11", "aaa-2.01"]

strArray.sort(function (a, b) {
    return a.localeCompare(b,undefined, {numeric: true, sensitivity: 'base'});
});

返回:

["aaa-0", "aaa-0.01", "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-2.01", "aaa-2.01", "aaa-11", "bbb-2.01"]

虽然我想:

["aaa-0", "aaa-0.01", "aaa-1.0", "aaa-1.01", "aaa-1.1", "aaa-2.01", "aaa-2.01", "aaa-11", "bbb-2.01"]

如何实现这一目标?即使我使用","而不是"。"排序是一样的。

2 个答案:

答案 0 :(得分:1)

您需要单独对数字和字母进行排序。

<强>样本

var strArray = ["aaa-0", "aaa-0.01", "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-2.01", "bbb-2.01", "aaa-11", "aaa-2.01"]

strArray.sort(function(a, b) {
  var splitA = a.split("-");
  var splitB = b.split("-");
  if (splitA[0] == splitB[0]) {
    return (Number(splitA[1]) - Number(splitB[1]));
  } else {
    return splitA[0].localeCompare(splitB[0], undefined, {
      numeric: true,
      sensitivity: 'base'
    });
  }
});
console.log(strArray);

答案 1 :(得分:0)

您可以将parameters中的标记ignorePunctuation设置为true

var array = ["aaa-0", "aaa-0.01", "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-2.01", "bbb-2.01", "aaa-11", "aaa-2.01"]

array.sort(function(a, b) {
    return a.localeCompare(b, undefined, { ignorePunctuation: true, numeric: true, sensitivity: 'base' });
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }