Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
2  
btw, new Array is evil, use [] literal syntax instead. –  hugomg Nov 8 '11 at 20:24
5  
The algorithm is specified here. Apart from that I'm not sure what else you want to know. –  Felix Kling Nov 8 '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 8 '11 at 20:30

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
    
+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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.