2014-10-08 41 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); 
};