2012-06-06 78 views

回答

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/

+0

謝謝,doc! :) – user1054134

+1

儘管布爾在排序方法中找到了一些成功,但[正確響應](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort#Description)是正數或負數,或者0.我以前也用過布爾語,直到我對它進行調用;) – Sampson

+0

好點,我會編輯 –

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"] 
+0

不需要'+','''已經轉換爲數字。 – georg

+0

@喬納森,這不會因爲在他的「單詞」部分出現一個數字而遭受風險嗎? –

+0

@ Dr.Dredel它確實需要他的值以他在這裏呈現的相同格式顯示。如果他們不這樣做,可能會出現問題。這就是說,我做了一個修改,只會匹配數值的* end *處的數字。 – Sampson

0

萬一有數字和下劃線的字(這是由JavaScript字定義完全合法的單詞字符:

arr.sort(function(_1, _2) 
{ 
    return +_1.substr(_1.lastIndexOf("_")+1)-_2.substr(_2.lastIndexOf("_")+1); 
}); 
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"] 

這被稱爲 「自然排序」。