Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

As3 Sorting Alphabetically and Numerically Simultaneously

So I have a sort method designed to sort values alphabetically which works great 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 though, when a title contains a number in it.

For example:

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

would sort to

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

but what I need to happen is for it to sort alphabetically but when it encounters a number a numeric value is taken into consideration and thus the sorting would return

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

I was hoping there was some sort of existing regex or algorithms built to do this but I am afraid I haven't the slightest clue what to search for. All my searches for sorting either does it alphabetically or numerically, not both.

thanks so much!

like image 530
rcooper102 Avatar asked Oct 04 '22 09:10

rcooper102


1 Answers

I found a JavaScript solution that translates to AS3: Sort mixed alpha/numeric array.

The solution would look something like:

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
like image 190
Corey Avatar answered Oct 20 '22 14:10

Corey