How Can I Sort An Array A Certain Way With Characters And Numbers In Javascript?
I want to sort array like this: ['AAAA1', 'AAAA3', 'ABAA2', 'AAAA10', 'AAAA100', 'BBB2', 'BBB10', 'BBAA3', 'BBB2AA'] when i sort it, returns me like: ['AAAA1', 'AAAA10', 'AAAA100'
Solution 1:
It seems you are treating digits differently, depending on where they appear in the string. If they are between characters, it seems they should be compared alphabetically and if they appear at the end they should be compared numerically. Please correct me if I'm wrong, but otherwise I cannot explain why BBB10
comes before BBB2AA
.
There is no "general method" for this kind of problem. You have to implement the logic to compare the values yourself. I.e. you have to split each value in its string and number part and compare the parts individually:
functionparseValue(v) {
// extract number (defaults to 0 if not present)var n = +(v.match(/\d+$/) || [0])[0];
var str = v.replace(n, ''); // extract string partreturn [str, n];
}
You can use that function in the .sort
callback:
arr.sort(function(a, b) {
a = parseValue(a);
b = parseValue(b);
// compare string part alphabeticallyvar result = a[0].localeCompare(b[0]);
// if the string part is the same, compare the number partreturn result === 0 ? a[1] - b[1] : result;
});
Post a Comment for "How Can I Sort An Array A Certain Way With Characters And Numbers In Javascript?"