Can someone explain to me why this code below:
var points = [
99.1,
100,
99.9
];
console.log(points.sort());
...log()
s this, unsorted array:
[100, 99.1, 99.9]
After sort()
, shouldn't the array be this below?
[100, 99.9, 99.1]
Can someone explain to me why this code below:
var points = [
99.1,
100,
99.9
];
console.log(points.sort());
...log()
s this, unsorted array:
[100, 99.1, 99.9]
After sort()
, shouldn't the array be this below?
[100, 99.9, 99.1]
From w3schools:
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function".