-3

here I try to sort integer array like

var points = [000, 100, 010, 101, 001, 011, 110, 111];

using points.sort(); but the output was 0,1,100,101,110,111,8,9. I was really confused with that, and 8,9 comes from where.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – elclanrs May 06 '14 at 08:24
  • __Always__ take a look at the documentation first. Questions like this are easily answered with a glance at the specifications of the function. – Cerbrus May 06 '14 at 08:28
  • 1
    @Bergi In fact not. See Daniel's good answer. – Denys Séguret May 06 '14 at 08:35
  • Oh, and don't "pad" your integers with leading zero's. That will give unexpected results. – Cerbrus May 06 '14 at 08:38
  • 1
    @dystroy: Oh, right, because it's two questions. For the second, see [Why does 0154 === 108?](http://stackoverflow.com/q/5000848/1048572) – Bergi May 06 '14 at 08:47

2 Answers2

3

8 is from 010, 9 is from 011, because they are interpreted as octal numbers

You need to remove the preceding zeros

And then you need to use the comparison function in sort() :

points.sort(function(a,b) { return a-b })
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Daniel Cheng
  • 820
  • 5
  • 14
1

That's because the default sorting is based on string comparison.

From the MDN :

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order

To sort numbers, do

points.sort(function(a,b) { return a-b })

EDIT : @Daniel pointed another problem, that is the fact your number literals aren't interpreted as you think they are, you should remove the non significant zeros.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758