5

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.

William Troup
  • 12,739
  • 21
  • 70
  • 98
  • If all the values are prefixed exactly the same, why not have a string prefix variable that is added on whenever it needs displaying and just store the numeric values? If they are different and variable then like kgb says you will need a natural sorting library. – Tom Gullen Jun 24 '10 at 09:14
  • Possible duplicate of [Javascript : natural sort of alphanumerical strings](https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) – Stephen Quan Sep 12 '17 at 22:21

3 Answers3

9

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"]);
Markus Johnsson
  • 3,949
  • 23
  • 30
1

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

vlood
  • 927
  • 6
  • 16
0

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

Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
  • it appears, this topic has been disussed... http://stackoverflow.com/questions/34518/natural-sorting-algorithm/34528#34528 – Sergey Eremin Jun 24 '10 at 09:13