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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With