Sort JavaScript String Array containing numbers

Solution 1:

You need to extract the numeric values from the strings and sort based on those, just like vlood said. For example, try this code:

function mySort(arr)
{
    var regex = /Value\s([0-9]+)/;

    function map(str) {
        return Number(regex.exec(str)[1]);
    }

    return arr
    .sort(
        function (a,b) {
            var av = map(a), bv = map(b);
            return av < bv ? -1 : av > bv ? 1 : 0;
        })
}

mySort(["Value 1", "Value 10", "Value 11", "Value 5"]);

Solution 2:

If you are enthusiastic about writing it yourself, you can just parse the items with an regular expression and compare the second part. Those will match something like

"Value\s[1-9][0-9]*"