按字母数字排序数组

时间:2019-03-14 04:14:08

标签: javascript

我的数组如下所示,我想通过字母数字的排序方式以更快的方式进行升序或降序。

[
  "NFO:BANKNIFTY1931428900CE",
  "NFO:BANKNIFTY1931429000CE",
  "NFO:BANKNIFTY1931429500CE",
  "NFO:BANKNIFTY1931429400CE",
  "NFO:BANKNIFTY1931429300CE",
  "NFO:BANKNIFTY1931429200CE"
]

我想按以下顺序对其进行排序,降序或升序

[
  "NFO:BANKNIFTY1931429500CE",
  "NFO:BANKNIFTY1931429400CE",
  "NFO:BANKNIFTY1931429300CE",
  "NFO:BANKNIFTY1931429200CE",
  "NFO:BANKNIFTY1931429000CE",
  "NFO:BANKNIFTY1931428900CE",
]

我尝试了以下类似操作,但是排序不正确,速度也很慢。

function sort() {
    var arr = disorderedArray;
    arr.sort(function(a, b) {
        a = a.split(" ");
        b = b.split(" ");
        var an = parseInt(a[0], 10);
        var bn = parseInt(b[0], 10);
        return an < bn ? 1 : (an > bn ? -1 : (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0)));
    });
    console.log(arr.reverse());
}

注意:有时可能会混合使用小写字母。

2 个答案:

答案 0 :(得分:5)

只需使用.sort()

var items = [
  "NFO:BANKNIFTY1931428900CE",
  "NFO:BANKNIFTY1931429000CE",
  "NFO:BANKNIFTY1931429500CE",
  "NFO:BANKNIFTY1931429400CE",
  "NFO:BANKNIFTY1931429300CE",
  "NFO:BANKNIFTY1931429200CE"
]
var sorted = items.sort()
console.log(sorted);

答案 1 :(得分:3)

使用localeCompare方法按字母数字顺序对数组进行排序。

localeCompare()方法返回一个数字,该数字指示参考字符串是按排序顺序位于给定字符串之前还是之后还是与给定字符串相同。

const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log([
  "NFO:BANKNIFTY1931428900CE",
  "NFO:BANKNIFTY1931429000CE",
  "NFO:BANKNIFTY1931429500CE",
  "NFO:BANKNIFTY1931429400CE",
  "NFO:BANKNIFTY1931429300CE",
  "NFO:BANKNIFTY1931429200CE"
].sort(sortAlphaNum))