Skip to content Skip to sidebar Skip to footer

Javascript - Sort Letter Number Combination

I have a combination of letters and numbers. For example: 2E12, 1Z10, 3D13, 3D03, FB14, X002, etc. I've tried a handful of methods to sort these strings, but nothing seems to work.

Solution 1:

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 interpolationfunctionnatSort(as, bs){
    var a, b, a1, b1, i= 0, L, rx=  /(\d+)|(\D+)/g, rd=  /\d/;
    if(isFinite(as) && isFinite(bs)) returnas - bs;
    a= String(as).toLowerCase();
    b= String(bs).toLowerCase();
    if(a=== b) return0;
    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;
            }
            elsereturn a1> b1? 1: -1;
        }
    }
    return a.length - b.length;
}

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

s.sort(natSort)

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

Post a Comment for "Javascript - Sort Letter Number Combination"