Practice exercise - functions and arrays #36

Hi All,

While trying to Practice Exercise no. 35 for Built-in array methods, I see a rather weird phenomenon. In the example given, there is a typo where it introduces some extra spaces for K, i.e. it introduces " K " as an element to an array instead of “K”. The exercise asks for sorting the alphabets.

Interestingly, I see that " K " is evaluated as less than “K” or even “A”.

And hence after I implement the sort function of the array of all the alphabets, I am continuing to see " K " starting earlier than “A”.

Can anybody throw some more light on this?

Cheers’
– Rays

I have tried with trimming the space but still the result does not change.

Hi @Chin,

That’s a very good question.

Well, the “in” keyword prints out the indexes. Where as, “of” keyword prints out the values from the beginning of the array.

“num” here, only stores the indexes. so essentially, in the loop you are checking it in this order –
smallest – > 6 (initially)
0 < 6 -> returns true, therefore change smallest to 0
1 < 0 -> returns false
2< 0 -> returns false


and so on.
And finally outputs 0. 0 is not there in your array list, it is just the index of the first item in your array.

Explained above.

Well, this is just a happy coincidence. smallest = list[num] should not be used. Start using bigger numbers in your array and you will see problems start arising. For example -
This array will break the code and return undefined as your answer . const list = [6, 4, 11, 7, 12, 8, 3, 9, 1];

Hope this clarifies your doubt.

Hi @rays,
The precedence of comparison is given to empty space more. So make sure to remove any space available between the letters and try it out. The comparison happens letter to letter in the string. And an empty space is also considered a letter in a string.

Hope this helps. :smile:

1 Like

Hi @Malik, I have tried with trim function to remove the spaces and then do the comparison, but strangely even then it did not work out. Not sure what I did wrong.

Can you paste your code here please. I will take a look at it.

Hi @Malik,

I think I have now identified the bug in the code. I am able to trim the spaces and it is now working fine :slight_smile:

Cheers
–Rays

1 Like

Is this the forum if you have a query regarding exercise 35?