如何在JavaScript中对浮点数组进行排序?

Son*_*dhu 1 javascript sorting

我试过下面的例子,但现在正在使用正确的信息.

var fruits = [110.111, 1245.22222, 2.458, 0.001];
fruits.sort();
document.write(fruits);
Run Code Online (Sandbox Code Playgroud)

结果:

0.001,110.111,1245.22222,2.458
Run Code Online (Sandbox Code Playgroud)

但是我想要这样的东西

0.001,2.458,110..111,1245.22222
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?

Tha*_*you 6

array.sort( [compareFunction] )接受一个可选函数,作为自定义比较器

fruits.sort(function(a, b){
  return a - b;
});
Run Code Online (Sandbox Code Playgroud)

如果你想降序排序

fruits.sort(function(a, b){
  return b - a;
});
Run Code Online (Sandbox Code Playgroud)

via:MDN Array.prototype.sort docs

  • 如果compareFunction(a, b)小于0,则将a排序为低于b的索引,即a先到.
  • 如果compareFunction(a, b)返回0,则保持a和b相对于彼此保持不变,但是对于所有不同的元素进行排序.注意:ECMAscript标准不保证这种行为,因此并非所有浏览器(例如可追溯到至少2003年的Mozilla版本)都尊重这一点.
  • 如果compareFunction(a, b)大于0,则将b排序为低于a的索引.
  • compareFunction(a, b)当给定一对特定元素a和b作为其两个参数时,必须始终返回相同的值.如果返回不一致的结果,则排序顺序未定义

最近,我一直在做一些函数式编程.对于想要以不同方式解决同一问题的人,我会将此部分作为另一种选择.

首先,我们有一些通用的实用功能.当我们想要定义更高阶ascdesc排序函数时,这些是必要的.

const sub = x => y => y - x;
const flip = f => x => y => f (y) (x);
const uncurry = f => (x,y) => f (x) (y);
const sort = f => xs => xs.sort(uncurry (f));
Run Code Online (Sandbox Code Playgroud)

现在您可以轻松定义ascdesc根据sub

const asc = sort (flip (sub));
const desc = sort (sub);
Run Code Online (Sandbox Code Playgroud)

看看这个

asc ([4,3,1,2]);  //=> [1,2,3,4]
desc ([4,3,1,2]); //=> [4,3,2,1]
Run Code Online (Sandbox Code Playgroud)

您仍然可以使用自定义排序 sort (comparator) (someData)

// sort someData by `name` property in ascending order
sort ((a,b) => a.name - b.name) (someData); //=> ...
Run Code Online (Sandbox Code Playgroud)