使用Javascript - 排序字母数字组合 [英] Javascript - Sort Letter Number Combination

查看:133
本文介绍了使用Javascript - 排序字母数字组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字母和数字的组合。例如:2E12,1Z10,3D13,3D03,FB14,X002等

I have a combination of letters and numbers. For example: 2E12, 1Z10, 3D13, 3D03, FB14, X002, etc.

我试过的方法对这些字符串进行排序了一把,但似乎没有任何工作。 parseInt函数工作在团块但整个阵列从未排序(它是一个JSON数组),如果排序是第二次运行不同的结果出现。

I've tried a handful of methods to sort these strings, but nothing seems to work. parseInt works in clumps but the whole array is never sorted (it is a json array) and different results appear if the sort is run a second time.

我也使用正则表达式替换所有数字字母的尝试,但是这创造了一个逻辑错误。中的每个字符串中间的大字母替换它时间增加了由10个或20。例如一个因数的数量,1Z10将产生12610,即使它以1开始,并且应当排序朝向顶部

I've also tried using regex to replace all of the letters with numbers, but this creates a logic error. Each time a large letter in the middle of the string is replaced it increases the number by a factor of 10 or 20. For example, 1Z10 would create 12610 even though it starts with a 1 and should sort towards the top.

有谁知道如何把这些字符串进行排序?如果这封信是第一个或数第一,只要我可以从随机smatterings脱身没关系。

Does anyone know of how to sort these strings? It doesn't matter if the letter is first or the number is first, as long as I can get away from the random smatterings.

在此先感谢!

推荐答案

如果你想要的数字序列进行排序,好像他们是数字,阿尔法前
使100种2后,你需要什么是所谓的自然排序 -

if you want digit sequences to sort as if they were numbers, before alphas and so that 100 sorts after 2, you need what is called a natural sort-

这是一个例子,谷歌会发现更多。

This is one example, Google will find more.

// case insensitive, digits to number interpolation

function natSort(as, bs){
    var a, b, a1, b1, i= 0, L, rx=  /(\d+)|(\D+)/g, rd=  /\d/;
    if(isFinite(as) && isFinite(bs)) return as - bs;
    a= String(as).toLowerCase();
    b= String(bs).toLowerCase();
    if(a=== b) return 0;
    if(!(rd.test(a) && rd.test(b))) return a> b? 1: -1;
    a= a.match(rx);
    b= b.match(rx);
    L= a.length> b.length? b.length: a.length;
    while(i < L){
        a1= a[i];
        b1= b[i++];
        if(a1!== b1){
            if(isFinite(a1) && isFinite(b1)){
                if(a1.charAt(0)=== "0") a1= "." + a1;
                if(b1.charAt(0)=== "0") b1= "." + b1;
                return a1 - b1;
            }
            else return a1> b1? 1: -1;
        }
    }
    return a.length - b.length;
}

变种S =2E12,1Z10,1Z2,3D13,3D03,FB14,X002'.split(,);

var s= '2E12, 1Z10, 1z2, 3D13, 3D03, FB14, X002'.split(', ');

s.sort(natSort)

s.sort(natSort)

/*  returned value: (Array)
1z2,1Z10,2E12,3D03,3D13,FB14,X002
*/

这篇关于使用Javascript - 排序字母数字组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆