Nested loop - why is output shown 3x?

Hi everyone,

I have a problem with the output of a nested loop. The goal is to push only the words from the variable story to the variable betterWords, if they are not equal unnecessaryWords. But this doesn’t happen with the code below - can someone explain why and give me an alternative solution? Thanks!

let story = ‘Last weekend, I took literally the most beautiful bike ride of my life. The route is called “The 9W to Nyack” and …’,
let unnecessaryWords = [‘extremely’, ‘literally’, ‘actually’ ];
const betterWords = ;

const storyWords = story.split(’ ');

for (let i = 0; i < storyWords.length; i++) {
for (let j = 0; j < unnecessaryWords.length; j++) {
if (unnecessaryWords[j] !== storyWords[i]) {
betterWords.push(storyWords[i])
};} }

console.log(betterWords);

Hi! welcome to the forums :slight_smile:

Remember to format your code with </> before pasting. It makes it easier for people to read (specially with nested loops).

On the topic of loops, whenever you nest the complexity goes up. It’s important to have a firm grasp of how the loops are functioning. Log statements can go a long way to helping you visualize what’s happening inside your loops.

Part of the the craft of making the code work is how to help yourself understand how it’s currently working, so you can bridge the distance to how you actually want it to work. I find that simple, understandable steps help to start out, and then you can build complexity. But starting out complex 95% of the time will not be a productive way to fix things.

These are some possible statements you can run, you may need more though for yourself.

for (let i = 0; i < storyWords.length; i++){
    console.log(storyWords[i]);
}
//or

for (let i = 0; i < storyWords.length; i++){
    for (let j = 0; j < unnecessaryWords.length; j++){
        console.log(unnecessaryWords[j]);
    }
}

//or

for (let i = 0; i < storyWords.length; i++){
    for (let j = 0; j < unnecessaryWords.length; j++){
        console.log(unnecessaryWords[j] !== storyWords[i]);
    }
}
2 Likes

Yeah !! that’s it bro

OK, thanks for not answering the question :slight_smile:

1 Like

No !! not like that , i am not sure 100% about the correct answer that’s why ! i am also beginner in JavaScript !

Haha…no problem… I’m a beginner as well…doing the web development-course here on Codecademy. But I find some of the exercises quite complex. Hope to get better and come back with the solution soon :wink:

1 Like

Yeah !! We’re here for help each other as a beginners . :smiling_face_with_three_hearts: :smiling_face_with_three_hearts: :smiling_face_with_three_hearts: