How to sort an array of floats in JavaScript?

后端 未结 4 1072
甜味超标
甜味超标 2021-01-15 21:10

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


        
相关标签:
4条回答
  • 2021-01-15 21:57

    You can define the sorting function:

    fruits.sort(function(a,b) {return a>b})
    
    0 讨论(0)
  • 2021-01-15 22:03

    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); //=> ...
    
    0 讨论(0)
  • 2021-01-15 22:05

    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.

    0 讨论(0)
  • 2021-01-15 22:08

    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.

    0 讨论(0)
提交回复
热议问题