Reputation: 63
quick question. Does the .sort method in javascript automatically sort items in an array using ASCII order. I've looked at examples etc but haven't seen a definitive answer anywhere. Also what alternative ways of alphabetically sorting an array is there?
Thanks in advance
Upvotes: 3
Views: 8651
Reputation: 20782
Unless you are using "ASCII" like "Kleenex" (vs facial tissue), no, nothing in JavaScript is ASCII. In particular, strings are counted sequences of UTF-16 code units, one or two of which encode a Unicode codepoint. (This applies to Java, .NET, JavaScript, HTML, XML,….)
A lexicographic ordering is not very useful for human-valued text. Since you ask about alphabetically sorting, you must have a particular language's writing system's alphabet in mind. So, perhaps you want to pass localeCompare
to sort
.
Upvotes: 0
Reputation: 21575
Yes. If you look at the .sort()
method on MDN it states the case when the compare function parameter is omitted:
Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
Since Unicode is a super set of ASCII then yes it does sort in ASCII order.
Upvotes: 8