使用word_number值排序javascript数组

时间:2012-06-06 20:08:09

标签: javascript jquery

如何对数组进行排序

var arr = new Array("word_12", "word_59", "word_17");

所以我得到了

["word_12", "word_17", "word_59"]

谢谢!

4 个答案:

答案 0 :(得分:4)

您需要编写一个排序方法(您可以编写任何您喜欢的方法),它将_上的字符串拆分并使用第二部分作为数字排序值。

​    function sortOnNum(a,b){
         //you'll probably want to add a test to make sure the values have a "_" in them and that the second part IS a number, and strip leading zeros, if these are possible
         return (a.split("_")[1] * 1 > b.split("_")[1] * 1)? 1:-1;// I assume the == case is irrelevant, if not, modify the method to return 0 for ==
    }

    var ar = new Array ("foo_1", "foo_19", "foo_3", "foo_1002");

ar.sort(sortOnNum); //here you pass in your sorting function and it will use the values in the array against the arguments a and b in the function above

alert(ar); // this alerts "foo_1,foo_3,foo_19,foo_1002"

这是一个小提琴: http://jsfiddle.net/eUvbx/1/

答案 1 :(得分:2)

以下假设您的号码始终位于字符串的最后。请注意,我在数组中添加了一些其他示例,以演示可以使用的不同格式:

var numbers = ["word_12", "word_59", "word_17", "word23", "28", "I am 29"];

numbers.sort(function(a,b){
    return a.match(/\d+$/) - b.match(/\d+$/);
});

结果是:

["word_12", "word_17", "word23", "28", "I am 29", "word_59"]

答案 2 :(得分:0)

以防万一在单词中有数字和下划线(javascript单词定义是非常合法的单词字符:

arr.sort(function(_1, _2)
{
    return +_1.substr(_1.lastIndexOf("_")+1)-_2.substr(_2.lastIndexOf("_")+1);
});

答案 3 :(得分:0)

以下是一般情况的代码:

natcmp = function(a, b) {
    var aa = [], bb = [];

    (a + "").replace(/(\d+)|(\D+)/g, function($0, $1, $2) { aa.push($2 || Number($1)) });
    (b + "").replace(/(\d+)|(\D+)/g, function($0, $1, $2) { bb.push($2 || Number($1)) })

    var la = aa.length, lb = bb.length;

    for (var i = 0; i < Math.max(la, lb); i++) {
        if (i >= lb) return 1;
        if (i >= la) return -1;
        if (aa[i] > bb[i]) return 1;
        if (aa[i] < bb[i]) return -1;
    }

    return 0;
}

示例:

var x = ["word_12", "word_59", "ford_1a", "ford_12a", "ford_2a", "word_0", "word_"];
x.sort(natcmp)

# ["ford_1a", "ford_2a", "ford_12a", "word_", "word_0", "word_12", "word_59"]

这称为“自然分类”。