karan satia karan satia - 7 months ago 24
Javascript Question

javascript loop iterating too much

Trying a fun problem of replacing vowels in a string with the next vowel in line aka a->e, e->i, i->o, o->u, not accounting for "u". Starting with an array instead of a string. My second loop (to iterate over vowel array elements) is ignoring my "j

var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
for (var j = 0; j<vowelArray.length; j++) {
if (stringToChange[i]===vowelArray[j]) {
var newCharacter = vowelArray[j+1]
stringToChange[i] = newCharacter
i++
}
}
}
return stringToChange
};


I'm using node-debug to set breakpoints in a browser, and j is looping to 5 before starting over at 0. I get the correct output, but j should stop at 4...

Answer

Assuming vowelArray is 0-indexed...

var vowelChange = function(vowelArray, stringToChange) {
    for (var i = 0; i<stringToChange.length; i++) {
        for (var j = 0; j<vowelArray.length - 1; j++) {
            if (stringToChange[i]===vowelArray[j]) {
                stringToChange[i] = vowelArray[j+1];
                break;
            }
        }
    }
    return stringToChange
};
Comments