How to sort an array of floats in JavaScript?

2020-03-30 06:09发布

I tried below example but now working with correct information.

var fruits = [110.111, 1245.22222, 2.458, 0.001];
fruits.sort();
document.write(fruits);

Result :

0.001,110.111,1245.22222,2.458

But I want something like this

0.001,2.458,110..111,1245.22222

What wrong with this code?

4条回答
对你真心纯属浪费
2楼-- · 2020-03-30 06:53

Use Custom Function for sorting.

To sort it you need to create a comparator function taking two arguments and then call the sort function with that comparator function as follows:

fruits.sort(function(a,b) { return parseFloat(a) - parseFloat(b) } );

If you want to sort ascending change parseInt(a) - parseInt(b) and parseInt(b) - parseInt(a). Note the change from a to b.

查看更多
混吃等死
3楼-- · 2020-03-30 06:55

You can use a custom sort function like this:

fruits.sort(function (a,b) {return a - b;});

Array.sort() method treats numbers as strings, and orders members in ASCII order.

查看更多
唯我独甜
4楼-- · 2020-03-30 07:08

You can define the sorting function:

fruits.sort(function(a,b) {return a>b})
查看更多
够拽才男人
5楼-- · 2020-03-30 07:16

array.sort([compareFunction]) takes an optional function which works as a custom comparator

fruits.sort(function(a, b){
  return a - b;
});

If you want to sort descending

fruits.sort(function(a, b){
  return b - a;
});

via: MDN Array.prototype.sort docs

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always returns the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

Lately, I've been doing some functional programming. I'll leave this section as another option for people that want to solve the same problem in different ways.

First we have some general utility functions. These will be necessary when we want to define our higher order asc and desc sorting functions.

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));

Now you can easily define asc and desc in terms of sub

const asc = sort (flip (sub));
const desc = sort (sub);

Check it out

asc ([4,3,1,2]);  //=> [1,2,3,4]
desc ([4,3,1,2]); //=> [4,3,2,1]

You can still do a custom sort using sort (comparator) (someData)

// sort someData by `name` property in ascending order
sort ((a,b) => a.name - b.name) (someData); //=> ...
查看更多
登录 后发表回答