Skip to content
Advertisement

How can I log the index of each array item?

I’m a beginner and struggling with this exercise. 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');

Advertisement

Answer

You could take the index i from the loop directly.

String#indexOf returns the first found index, but if you take an index as second parameter it searches from this position.

const subLength = (word, letter) => {
  let wordArray = word.split("");
  let indexArray = [];
  for (let i = 0; i < wordArray.length; i++) { // take let here too
    if (wordArray[i] === letter) {
      indexArray.push(i);
    }
  }
  console.log(indexArray);
}

subLength('Saturday', 'a');

An approach without using split.

const
    subLength = (word, letter) => {
        let indexArray = [];
        for (let i = 0; i < word.length; i++) {
            if (word[i] === letter) indexArray.push(i);
        }
        console.log(indexArray);
    };

subLength('Saturday', 'a');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement