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');
indexOf()always returns the index of the first element that matches. You should rather just push i.indexArray.push(i)indexOfat all?iis already the index you want.