Number 6. Log It!, passed through the assignment but console displayed many more names than appeared in text


#1

Code by Student:
/*jshint multistr:true */
var text = "Ewan was walking through the woods \
with his friends for a while. They were having\
lots of fun with Ewan, and Ewan and his friends."

var myName = "Ewan"

var hits = []
for (i = 0; i < text.length; i++) {
if (text[i] === "E") {
for (j = i; j < i + myName.length; j++){
hits.push("Ewan")
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!")
}
else {
console.log(hits)
}
Console display:

[ 'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan',
'Ewan' ]

Finally any advice on why there might be so many names when mine is only mentioned a few times? Also I appreciate critique on structure and spacing, thank you for your time whoever responds.


#2

Hey there, instead of
hits.push("Ewan")

Try replacing it with

hits.push(text[j]);

This way the program will push the letters that follow the first letter of your name into the array, not just the text of your name.

Let me know how this works!


#3

The 1st loop comes across an 'E' in the text string. 'E' appears 3 times and this triggers the 2nd loop each time. The 2nd loop will run 1 fewer time than the length of the myName variable + i, which comes to 4.

Now, hits.push("Ewan") shoves "Ewan" into the hits array 4 times during each 2nd loop pass. The 2nd loop is triggered 3 times because of the 1st loop.

4×3=12, the # of Evans in your array.


#4

Yes it has worked, thank you skier43. They ought to teach this in the schools


#5

I was having the same issue as Ewan, thanks for your explanation !


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.