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();
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();
Share
Improve this question
edited Nov 8, 2011 at 20:27
Felix Kling
818k181 gold badges1.1k silver badges1.2k bronze badges
asked Nov 8, 2011 at 20:22
abbasabbas
4323 gold badges10 silver badges22 bronze badges
3
-
2
btw,
new Array
is evil, use[]
literal syntax instead. – hugomg Commented Nov 8, 2011 at 20:24 - 6 The algorithm is specified here. Apart from that I'm not sure what else you want to know. – Felix Kling Commented Nov 8, 2011 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 Commented Nov 8, 2011 at 20:30
1 Answer
Reset to default 7From the MDN docs for sort():
If pareFunction is not supplied, elements are sorted by converting them to strings and paring strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" es before "9" in lexicographic order, but in a numeric sort 9 es before 80.
Refer to the answers of this question as to what algorithm is being used.