3

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

2

2 Answers 2

8

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.

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

1 Comment

Yes .sort() method is doing that. var stringArray = ['Blue', 'Humpback', 'Beluga']; console.log('Sorted:', stringArray.sort()); Result = Sorted: Beluga,Blue,Humpback
0

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.

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.