Learn Advanced Array Methods by Building a Statistics Calculator Step 21

I am confused by some of the information in the prompt on this step. I was able to pass the challenge but I am unsure what is trying to be conveyed by the first paragraph:

“By default, the .sort() method converts the elements of an array into strings, then sorts them alphabetically. This works well for strings, but not so well for numbers. For example, 10 comes before 2 when sorted as strings, but 2 comes before 10 when sorted as numbers.”

If .sort() converts the elements to strings, which are then evaluated by Unicode, shouldn’t 10 come second regardless (of being a string or number) because it has two characters? I understand that 1 is U+0031 and 2 is U+0032, but wouldn’t adding the 0 automatically make 10 ‘greater’ than 2 even with Unicode?

Nope - the default sort is alphabetically, an 10 comes before 2 in the “alphabet” as the comparison starts with the first characters, in this case 1 and 2.

Why doesn’t the 0 get taken into consideration though?

The 0 does get taken into consideration when comparing two values with two digits. ‘10’ and ‘15’ for example are sorted as you expect. But ‘20’ comes before ‘3’

The sorting alphabetically is left to right, like sorting ‘art’ and ‘arms’ even though they have different numbers of letters.

So if you have 20 and 3, it’ll drop the 0 because the other number is only one digit?

Sorry to keep asking. I just want to understand how this works lol.

Not really “drop the zero”. More of “the digits are compared left to right”.

How do you alphabetize “art” and “arms” even though those are different length words?

Left to right like you said.

Does it compare 1 digit at a time? Like 2 < 3 and then 0 == no digit?

instead of the entirety of twenty?

Right, and with 2 and 10 there is already an alphabetical sorting given by the leftmost “letter” so the sorting doesn’t need to consider any more “letters”.

Ohh okay. I finally understand. Thank you so much!

1 Like