1

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

4
  • 1
    indexOf() always returns the index of the first element that matches. You should rather just push i. indexArray.push(i) Commented May 10, 2021 at 20:42
  • 2
    Why use indexOf at all? i is already the index you want. Commented May 10, 2021 at 20:44
  • btw, why do you split the string? you could iterate the string without splitting/taking an array. Commented May 10, 2021 at 20:47
  • @NinaScholz I'm not sure, I think I did it without splitting the string first and something wasn't working. Fixing it probably had nothing to do with splitting it into a string but that's just the way I worked through it. I'll learn. Thanks for your answer! Commented May 13, 2021 at 12:42

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, thanks. I got confused because I tried indexArray.push(wordArray[i]) previously and it was only logging the actual letters not the indexes (indices??) Thanks for answering so quickly!
0

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

Comments

Your Answer

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.