最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort Alphanumeric String Descending - Stack Overflow

programmeradmin1浏览0评论

I need to sort an array of alphanumerical items as follows. From:

2 xxx
20 axxx
38 xxxx
20 bx
8540 xxxxxx

to:

8540 xxxxx
38 xxxx
20 axxx
20 bx
2 xxx

Thus, sorted descending with respect to the numbers, then ascending alphabetically. The numbers are always separated from the alphabetical characters (denoted "xxxx") by a single space, but the numbers are variable length.

I suspect I need to use some Regex in the sort() function and splitting off the numbers by the space then sorting it, but I don't know how to tie in the alphabetical sorting. Any code samples? Thanks so much!

I need to sort an array of alphanumerical items as follows. From:

2 xxx
20 axxx
38 xxxx
20 bx
8540 xxxxxx

to:

8540 xxxxx
38 xxxx
20 axxx
20 bx
2 xxx

Thus, sorted descending with respect to the numbers, then ascending alphabetically. The numbers are always separated from the alphabetical characters (denoted "xxxx") by a single space, but the numbers are variable length.

I suspect I need to use some Regex in the sort() function and splitting off the numbers by the space then sorting it, but I don't know how to tie in the alphabetical sorting. Any code samples? Thanks so much!

Share Improve this question asked Jun 10, 2013 at 3:13 zdebruinezdebruine 3,8076 gold badges33 silver badges52 bronze badges 1
  • Check out these answers to see if you can adapt the solution: stackoverflow./a/4321879/1375372 stackoverflow./a/11931192/1375372 stackoverflow./a/4340339/1375372 – Rob Grzyb Commented Jun 10, 2013 at 3:20
Add a ment  | 

2 Answers 2

Reset to default 6

No need for RegEx, because Array.sort() accepts custom function:

http://jsfiddle/EFGK9/

var arr=["2 xxx","20 axxx","38 xxxx","20 bx","8540 xxxxxx"];
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);

Something like this will work:

var arr = [
    "2 xxx",
    "20 axxx",
    "38 xxxx",
    "20 bx",
    "8540 xxxxxx"
    ];

arr.sort(function(a, b) {
    var aParts = a.split(" "),
        bParts = b.split(" "),
        aNum = +aParts[0],   // convert numeric parts
        bNum = +bParts[0];   // to actual numbers

    if (aNum > bNum)
        return -1;
    else if (aNum < bNum)
        return 1;
    else
        return aParts[1].localeCompare(bParts[1]);
});

Demo: http://jsfiddle/KLa2J/

发布评论

评论列表(0)

  1. 暂无评论