Mehdi Yeganeh
Mehdi Yeganeh

Reputation: 2129

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", "AAAA3", "ABAA2", "BBAA3", "BBB10", "BBB2", "BBB2AA"]

That i like to sort it like this:

["AAAA1", "AAAA3", "AAAA10", "AAAA100", "ABAA2", "BBAA3", "BBB2", "BBB2AA", "BBB10"]

so i searched it in stackoverflow and i found something like under links but all of that haven`t general method for sorting characters & numbers string and only works for special questions!!

javascript: sort an array a certain way with integers and characters

How to sort number in javascript sort method

How to sort an array of integers correctly

Edit1:

Please check answers of questions in Sort JavaScript String Array containing numbers, the answer works with text with format var regex = /Value\s([0-9]+)/; and or in Sort mixed alpha/numeric array the answer only works with one character at the beginning of the string.. that i need some method works with all possible string that contains characters and numbers ...!!

Edit2:

Tanx Felix Kling:

i`m so sorry, i have wrong order to array in example, so i liked to BBB2AA order before BBB10

I found the general method for doing that with add leading zero, i wrote a version of it now and please optimize it or give me another options for sorting like that http://jsfiddle.net/Qd8nd/

Upvotes: 1

Views: 3355

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

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:

function parseValue(v) {
    // extract number (defaults to 0 if not present)
    var n = +(v.match(/\d+$/) || [0])[0]; 
    var str = v.replace(n, '');  // extract string part
    return [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 alphabetically
    var result = a[0].localeCompare(b[0]);
    // if the string part is the same, compare the number part
    return result === 0 ? a[1] - b[1] : result;
});

Upvotes: 1

Related Questions