2015-04-05 43 views
2

我有逗号分隔的浮点数。将浮点数排序为自然数

var example = "1.1, 1.10, 1.2, 3.1, 3.14, 3.5"; 

,我想这个浮点数像排序,

"1.1, 1.2, 1.10, 3.1, 3.5, 3.14" 
在我的情况

实际上,这是小数后的数字将考虑作为一个自然数,所以1.2将考虑为“2”而1.10会被认为是'10',这就是为什么1.2会首先超过1.10。

和建议或例子将是伟大的我,谢谢。

其实我想先根据小数前的数字对数组进行排序:)然后上面的逻辑就会运行。

回答

5

您可以使用.sort自定义比较函数,像这样

var example = "1.1, 1.10, 1.2, 3.1, 3.14, 3.5"; 
 

 
var res = example.split(',').sort(function (a, b) { 
 
    var result; 
 
    
 
    a = a.split('.'), 
 
    b = b.split('.'); 
 

 
    while (a.length) { 
 
    result = a.shift() - (b.shift() || 0); 
 
    
 
    if (result) { 
 
     return result; 
 
    } 
 
    } 
 

 
    return -b.length; 
 
}).join(','); 
 

 
console.log(res);

+0

完美(Y)谢谢男人 – 2015-04-05 09:51:22

2

您需要一个自定义的排序函数,它首先比较小数点前的数值,然后比较小数点后面的数值,以防它们相等。

example.split(", ").sort(function (a, b) { 
    var aParts = a.split(".", 2); 
    var bParts = b.split(".", 2); 
    if (aParts[0] < bParts[0]) return -1; 
    if (aParts[0] > bParts[0]) return 1; 
    return aParts[1] - bParts[1]; // sort only distinguishes < 0, = 0 or > 0 
}).join(", "); 
+0

你的例子正与1位小数后,不超过1个位数。这里是你的示例实现:) http://jsbin.com/qolapumaxa/1/edit – 2015-04-05 09:49:29

+0

你应该简单地将'console.log'作为上述表达式的值。我分别得到了1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,1.10,1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,2.1,2.2,2.3,2.4,2.5,2.6等等,2.7,2.8,2.9,2.10,2.11,3.1,3.2,3.3,3.4,3.5,3.6,3.7'。 – 2015-04-05 09:55:25

+0

当然,如果您的输入可以有多个小数点,例如'1.2.34',那么你应该使用亚历山大的代码。但你最初的问题没有提到这种可能性。 – 2015-04-05 09:58:17