I can't seem to figure this one out.
var arr = [2.62, 111.05, 1.05]
arr.sort();
This returns [1.05, 111.05, 2.62], but I'm expecting [1.05, 2.62, 111.05].
How can this be achieved? I've read a bit about writing a custom sort to split the "decimal" but haven't managed to have any success.
sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.
Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order. To sort the array in descending alphabetical order, you should provide the Collections interface method reverseOrder () as the second argument.
We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.
By default sorting is alphabetically. You need to pass a function to the sort
method
arr.sort(function(a, b){return a-b;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With