1

I'm a beginner trying to solve this kata:

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

My solution seems to be working until it encounters a whitespace in the given string, then it includes those as an element of the positions array. I know this is probably fixable by just filtering out the whitespaces but I would really like to know why my code isn't working.

function alphabetPosition(text) {
 const alphabet="abcdefghijklmnopqrstuvwxyz".split('');
 const letters = text.toLowerCase().split('');
 let positions =[];
 for (i=0; i<letters.length; i++){
 if (!(alphabet.includes(letters[i]))){
 continue;
 }
 positions[i]=(alphabet.indexOf(letters[i])+1); 
 }
 return (positions.join(' ')); 
}

I thought by using continue, it should just skip over the whitespaces within the letters array but the continue keyword seems to not have any effect. I have tried to look up the correct use of continue and really can't find my mistake. Any help would be much appreciated, thanks in advance!

jarmod
79.9k18 gold badges132 silver badges137 bronze badges
asked Dec 8, 2023 at 22:49
4
  • why dont you just check if letters[i]==' ' and then continue Commented Dec 8, 2023 at 22:54
  • 2
    look closer what happens to the variable i after you continue. And what the next position[i] would be. Commented Dec 8, 2023 at 22:56
  • @GreenChicken There are other non-letters besides spaces. Commented Dec 8, 2023 at 23:05
  • 1
    There's no need to convert alphabet or text to arrays. You can index a string with [i], and you can use includes() and indexOf() with strings. Commented Dec 8, 2023 at 23:07

1 Answer 1

1

The continue command does skip the execution of the following commands in the loop, but the loop counter i is still increased. When you use positions with indexes, the gap in the indexes that results from that can be seen when using join.

Use push() to build up the positions array instead of indexes to prevent gaps.

for (i=0; i<letters.length; i++){
 if (!(alphabet.includes(letters[i]))){
 continue;
 }
 positions.push(alphabet.indexOf(letters[i])+1); 
}
answered Dec 8, 2023 at 22:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.