Can someone explain why sort() works this way?. Thanks in advance

Can someone explain why sort() works this way?. Thanks in advance
0.0 0

#1

var arr = [1000, 1001, 857, 1];
var newarr = arr.sort();
console.log(newarr);

Result:

[1, 1000, 1001, 857]


#2

By default, sort() does a lexical (alphabetical) ordering.


#3

@davidradon

What @ArielLeslie has told you.

Everything that starts with a 1.
Then 1000 is larger than 1.
1001 is the next differentiat-or.
8 is larger than one so it is last no matter what follows.

So in lexical it looks at the first char, if necessary it will go to the second, the third, the fourth but only if necessary.

1 (first char is equal, compare the second, wait there is no second char, it wins)
10 (first char is equal compare the second)
11 (first char is equal compare the second)
12 (first char is equal compare the second)
2 (unique and understandable pattern from here)
3
4
5
6
7
8
9

-WWC