简体   繁体   English

对包含数字的JavaScript String Array进行排序

[英]Sort JavaScript String Array containing numbers

I have an array in JavaScript that contains the following: 我在JavaScript中有一个包含以下内容的数组:

  • ["Value 1", "Value 5". [“值1”,“值5”。 "Value 10", "Value 11"]; “价值10”,“价值11”];

How would I go about sorting this array so that it does not appear as follows: 我将如何排序此数组,使其不显示如下:

  • ["Value 1", "Value 10". [“值1”,“值10”。 "Value 11", "Value 5"]; “价值11”,“价值5”];

But as: 但是:

  • ["Value 1", "Value 5". [“值1”,“值5”。 "Value 10", "Value 11"]; “价值10”,“价值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. 您需要从字符串中提取数值并根据这些值进行排序,就像vlood所说的那样。 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]*" “值\\ 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. 我不认为js中有内置的实现,但你可以使用一些库。 for example: phpjs - natcasesort 例如: phpjs - natcasesort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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