Trying to use .splice but doesn't work

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-loops/projects/whale-talk

Hello guys,

I want try other way to finish the whale talk. I try to finish it with .splice to learn how it work.
I have an issues, my code doesn’t work and I don’t understand why, can you help me?


let sentence = 'you are amazing';


let result = [];

for(let i = 0; i < sentence.length; i++){
    if(sentence[i] === 'a' || sentence[i] === 'e' || sentence[i] === 'i' || sentence[i] === 'o' || sentence[i] === 'u'){
        result.push(sentence[i]);
    }
}

for(let y = 0; y < result.length; y++){
    if(result[y] === 'u'){
       
       result.splice(y,0,'u');
    }
}


console.log(result);

Have you attempted to step through the code in your mind to understand the problem? This is a useful strategy. Take a really simple result:

result = ['u']

now lets walk through the loop:

for(let y = 0; y < result.length; y++){

result.length is one, so the loop will run. Then we insert the letter u to the result array using splice, so we get:

result = ['u', 'u']

so then for the next iteration of the loop we get:

y = 1; 1 < 2; y++ // y has increased to 1

and this a problem, the next element is again a u. Given we just inserted this letter to the array. And this problem will keep occurring.

So you would need to make the loop skip over the element you inserted.

Oh ! Your answer really helpful me. Now I understand my mistake.

Thank you so much