简体   繁体   中英

Sort JavaScript String Array containing numbers

I have an array in JavaScript that contains the following:

  • ["Value 1", "Value 5". "Value 10", "Value 11"];

How would I go about sorting this array so that it does not appear as follows:

  • ["Value 1", "Value 10". "Value 11", "Value 5"];

But as:

  • ["Value 1", "Value 5". "Value 10", "Value 11"];

Any help would be great.

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"]);

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]*"

you need natural sorting. i don't think there is a built-in implementation in js, but you can use some library. for example: phpjs - natcasesort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM