2

Does anyone know how the built-in JS function array.sort() functions internally? I mean does it change strings to numbers....etc

var keys = new Array();
keys.sort();
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
abbas
  • 424
  • 3
  • 10
  • 22
  • 2
    btw, `new Array` is evil, use `[]` literal syntax instead. – hugomg Nov 08 '11 at 20:24
  • 6
    The algorithm is specified [here](http://ecma262-5.com/ELS5_HTML.htm#Section_15.4.4.11). Apart from that I'm not sure what else you want to know. – Felix Kling Nov 08 '11 at 20:25
  • To answer the question: No, `.sort` will not change any element values, **unless** you specify a function which modifies the input. eg: `keys.sort(function(x,y){x.moo=1337; y.cowsay="bar";})` – Rob W Nov 08 '11 at 20:30

1 Answers1

7

From the MDN docs for sort():

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. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

Refer to the answers of this question as to what algorithm is being used.

Community
  • 1
  • 1
Daff
  • 43,734
  • 9
  • 106
  • 120
  • +1. Reading this just saved me from some hard to track bugs later in production. Too bad one can only favorite the question, and not the answers. – Milan Babuškov Jun 14 '12 at 16:15