排序的字母数字字符

排序的字母数字字符

本文介绍了排序的字母数字字符串降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要如下排序​​字母数字项目的数组。发件人:

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

2 xxx
20 axxx
38 xxxx
20 bx
8540 xxxxxx

8540 xxxxx
38 xxxx
20 axxx
20 bx
2 xxx

因此​​,分类就下降到了号,然后按字母顺序上升。数字总是从字母字符分隔(记为XXXX),由一个单一的空间,但数量也变长。

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.

我怀疑我需要使用正则表达式的一些由空间,然后排序它sort()函数和分裂出的数字,但我不知道如何在字母排序领带。任何code样?非常感谢!

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!

推荐答案

无需正则表达式,因为<$c$c>Array.sort()接受自定义函数:

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

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);

这篇关于排序的字母数字字符串降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:19