2014-10-08 42 views
0

我有元素的列表中的Javascript陣列如下:排序Javascript數組與字符串和數字

myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB",...] 

等。我想對可用空間中的數組進行排序,因此在上面的示例中,數據存儲區中的兩個將是數組中的第一個元素。該數組總是用「 - free space xx.xxGB」構造的,但是在某些情況下可用空間可能是5位數,例如xxx.xxGB。

任何人都可以幫助提供一種排序數組的方式嗎?我知道我可以使用類似

"*- free space\s[1-9][0-9]*GB" 

那麼這會不會像

myArray.sort("*- free space\s[1-9][0-9]*GB") ? 

這是正確的還是我會怎麼做呢?提前謝謝了。

回答

2

數字部分拉出在自定義排序功能,並減去:

myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore three - free space 6.23GB" ]; 
 

 
var re = /([0-9\.]+)GB/; // regex to retrieve the GB values 
 

 
myArray = myArray.sort(
 
    function(a, b) { 
 
     var ma = a.match(re); // grab GB value from each string 
 
     var mb = b.match(re); // the result is an array, with the number at pos [1] 
 
     
 
     return (ma[1] - mb[1]); 
 
    } 
 
); 
 

 
alert(myArray.join("\r\n"));

+0

這是更好的:'var re =/free space(\ d +(?:\。\ d + |))/' – hindmost 2014-10-08 20:36:53

+0

太好了 - 非常完美 - 非常感謝 – Oli 2014-10-08 20:39:07

1

這應該做的伎倆:

myArray.sort(function compare(a, b) { 
    var size1 = parseFloat(a.replace(/[^0-9\.]/g, '')); 
    var size2 = parseFloat(b.replace(/[^0-9\.]/g, '')); 
    if (size1 < size2) { 
    return -1; 
    } else if (size1 > size2) { 
    return 1; 
    } 
    return 0; 
}); 

Array.prototype.sort不接受一個正則表達式,它接受一個回調或將盡其所能基於數字/字母順序排列的排序,如果你沒有傳遞迴調

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

+0

什麼'回報尺寸1 - size2' – soktinpk 2014-10-08 20:37:01

+0

當然,這工作正常,並更加簡潔,但看到提問者被顯示排序功能的一個不完整的知識,我想我」 d是詳細的。 – 2014-10-08 20:38:31

+0

謝謝!這絕對有助於我。 – Oli 2014-10-08 20:40:03

1

這應該工作,以及如果你只想數字返回。

我用空格分割字符串並抓住最後一部分。 (#GB),然後我抓取除最後兩個字符以外的所有字符的子字符串(所以我砍掉GB),然後使用Javascript函數對剩餘的數字進行排序。

JSFiddle Demo

window.onload = function() { 
    myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore two - free space 16.23GB", "Datastore two - free space 6.23GB"]; 
    for (i = 0; i < myArray.length; i++) 
    { 
     var output = myArray[i].split(" ").pop(); 
     output = output.substring(0, output.length-2); 
     myArray[i] = output; 
    } 
    myArray.sort(function(a, b){return a-b}); 
    alert(myArray); 
};