3
[1, false, 10, "b", 3, "33", ":", "R", "^"].sort()

Yields the following sort:

[1, 10, 3, "33", ":", "R", "^", "b", false]

Can anyone explain how the sort method works? I'm guessing that it must be translating everything into ASCII.

The plot thickens when I do this

[1, false, 10, "b", 3, "33", ":", "R", "^"].sort(function(a,b) {return b-a})

Outputs the following:

[10, 1, false, "b", "33", 3, ":", "R", "^"]

Any method to this madness?

4
  • The default sort order is according to string Unicode code points. Commented Dec 9, 2015 at 17:19
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 9, 2015 at 17:20
  • 2
    Why can't you add some info on why you think it looks like madness e.g. show that it's not what you'd have thought it was Commented Dec 9, 2015 at 17:20
  • Totally. String unicode makes sense, but I thought that the native .sort and the sort(fn (a,b,) {return b-a}) would return the same order. Instead, the order is not even flipped in the second example. It is rearranged with regards to 10,1, and false. Commented Dec 9, 2015 at 21:48

1 Answer 1

6

From MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.

And:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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

Comments

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.