NicolaHearn
NicolaHearn

Reputation: 49

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');

Upvotes: 1

Views: 886

Answers (2)

Unmitigated
Unmitigated

Reputation: 89412

A simpler method would be to filter over the indexes.

const subLength = (word, letter) => [...Array(word.length).keys()]
  .filter(i => word[i] === letter);
console.log(subLength('Saturday', 'a'));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

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');

Upvotes: 2

Related Questions