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();
3
  • 2
    btw, new Array is evil, use [] literal syntax instead. 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. 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";}) Commented Nov 8, 2011 at 20:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.