I have an array of float point numbers:
[ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ]
After running sort() on the array I get this:
[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]
Notice how 5.8... is bigger than 49.6... for JavaScript (Node). Why is that?
How can I correctly sort this numbers?
sort(float[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of floats into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.
Pass in a sort function:
[….].sort(function(a,b) { return a - b;});
results:
[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049]
From MDN:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order.
The built in JS sort function treats everything as strings. Try making your own:
var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ); function sortFloat(a,b) { return a - b; } numbers.sort(sortFloat);
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