将浮点数排序为自然数

时间:2015-04-05 09:31:03

标签: javascript jquery sorting

我有逗号分隔的浮点数。

 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之后。

并且建议或示例对我来说都很棒,谢谢。

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

2 个答案:

答案 0 :(得分: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);




答案 1 :(得分: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(", ");