Alfonso Giron Alfonso Giron - 6 months ago 13
Javascript Question

For loop..if - Return true only after all intervals pass

A bit of a simple question, yet I can't figure it out. Perhaps I should be using a different method. I want to return true only after all the intervals in the for loop are run and pass the condition. However, as I have my code written, the return to true or false is done after the initial value of the loop.
The code tests if the letter 'z' is in the string 3 or less indices after a letter 'a'.
How can I fix/optimize my code?

function nearbyAZ(str) {
var aIndex = [];
if (str.length == 1) {
return false;
}
for (var i = 0; i < str.length; i++){
if (str[i] == 'a') {
aIndex.push(i);
}
}
for (var j = 0; j < aIndex.length; j++) {
if (str.indexOf('z') <= aIndex[j] + 3 && str.indexOf('z') >= aIndex[j]) {
return true;
}
else {
return false;
}
}

}

console.log(nearbyAZ("abfz")) //true
console.log(nearbyAZ("abannz")) //should return true but false is returned before the second 'a' can be tested
console.log(nearbyAZ("a")) //false
console.log(nearbyAZ("z")) //false
console.log(nearbyAZ("za")) //false

Answer

The reason why it is not working, is because you have to put your return false outside the loop.

When it hits a return it will go out of the function.

function nearbyAZ(str) {
    var aIndex = [];
    if (str.length == 1) {
        return false;
    }
    for (var i = 0; i < str.length; i++){
        if (str[i] == 'a') {
            aIndex.push(i);
        }
    }
    for (var j = 0; j < aIndex.length; j++) {
        if (str.indexOf('z') <= aIndex[j] + 3 && str.indexOf('z') >= aIndex[j]) {
            return true;
        }

    }
    return false;
}