Practice with loops and arrays help

Hello,

I am doing the second exercise in the loops, arrays, iterators intermediate practice but am stuck here.

Can anyone tell me why the console is logging the index of both characters as 1. I want it to log the character a every time it appears in the word. So for example, if we ran the function with the word ‘Saturday’ and ‘a’ as below, it should log an array [1,6]. Instead it is logging [1, 1].

const subLength = (word, letter) => {

  let wordArray = word.split("");

  let indexArray = []

  for (i=0; i<wordArray.length; i++) {

    if (wordArray[i]===letter) {

    indexArray.push(wordArray.indexOf(letter));

     }

  } console.log(indexArray);

}

  subLength('Saturday','a');

.indexOf() simply finds the first instance of a letter in an array and returns the index of that. Therefore the reason it becomes [1, 1] is because it is returning the index of the first instance of the letter, which is at index 1. This actually doesn’t need to be as complicated as using indexOf(), as you already have an element used in the loop, which is effectively tracking the “current” index. If you use this instead then your code will work.

Solution below if you can’t quite figure it out!

indexArray.push(i)

Thanks Adam, I switched it so the push part is indexArray.push([i]) and it is working. So now my code is like this and it all works just fine but when I check my answer codecademy is telling me I have a syntax error. Can you spot it?

const subLength = (word, letter) => {

  let wordArray = word.split("");

  let indexArray = []

  for (i=0; i<wordArray.length; i++) {

    if (wordArray[i]===letter) {

    indexArray.push([i]);

     }

  } console.log(indexArray);

if (indexArray.length === 2) {

 return indexArray[1] - indexArray[0] +1;

} else {

  return 0;

} 

}
  

  console.log(subLength('planetary','a'));

My best guess would be doing push([i]) not being quite accurate, as you’re making nested arrays unnecessarily. It still works as they are mini arrays of length 1, but not best practise. Try just push(i), and if that doesn’t work, I’m not sure what else it could be. Code runs fine on VS Code so I presume it’s a soft error i.e. and error flagged by codecademy’s checks to make sure you’re doing it correctly, rather than an actual coding error.

1 Like