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?
Use Custom Function for sorting.
You can use a custom sort function like this:
Array.sort()
method treats numbers as strings, and orders members in ASCII order.You can define the sorting function:
array.sort([compareFunction]) takes an optional function which works as a custom comparator
If you want to sort descending
via: MDN Array.prototype.sort docs
compareFunction(a, b)
is less than 0, sort a to a lower index than b, i.e. a comes first.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.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 undefinedLately, 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
anddesc
sorting functions.Now you can easily define
asc
anddesc
in terms ofsub
Check it out
You can still do a custom sort using
sort (comparator) (someData)