0

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]
core
  • 32,451
  • 45
  • 138
  • 193

1 Answers1

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".

http://www.w3schools.com/jsref/jsref_sort.asp

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
Attila Szasz
  • 3,033
  • 3
  • 25
  • 39
  • It is nice explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – localghost Jan 22 '15 at 17:47
  • Yes, `sort` by default will sort `100` before `99`, but that is not what the OP is asking. He is wondering why it sorts `99.1` before `99.9`, and the answer is, well, that's the correct sort order even with a string comparison. –  Jan 22 '15 at 18:10