As3 Sort alphabetically and number simultaneously

So, I have a sorting method designed to sort the values ​​alphabetically, which works fine in almost all cases:

function alphabetical(name1, name2):int { 
        if (name1 < name2){ 
            return -1; 
        } else if (name1 > name2){ 
            return 1; 
        }else { 
            return 0; 
        };
    };

The problem is that when the header contains a number in it.

For instance:

['abc 8','abc 1','abc 10']

will be sorted into

['abc 1','abc 10','abc 8']

but I need it to be sorted in alphabetical order, but when it encounters a number, the numeric value is taken into account, and so sorting returns

['abc 1','abc 8'.'abc 10']

I was hoping there would be some existing regular expression or algorithms for this, but I'm afraid that I don't know what to look for. All my sort searches are done in alphabetical or digital form, and not both.

Many thanks!

+5
source share
1 answer

JavaScript, AS3: / .

:

var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
    var aA = a.replace(reA, "");
    var bA = b.replace(reA, "");
    if(aA === bA) {
        var aN = parseInt(a.replace(reN, ""), 10);
        var bN = parseInt(b.replace(reN, ""), 10);
        return aN === bN ? 0 : aN > bN ? 1 : -1;
    } else {
        return aA > bA ? 1 : -1;
    }
}

var arr = ['abc 8','abc 1','abc 10'];
arr.sort(sortAlphaNum);

trace(arr); // abc 1,abc 8,abc 10
+4

All Articles