Matthew Daly Matthew Daly - 4 months ago 8
Javascript Question

for loop only looping once

My question is concerning a

for
loop that appears to be looping only once and I'm not sure why.

I'm writing a function that compares the last letter of an array element to the first letter of the next array element.

My test input is the array: ["Buddy Bear","Romeo", "Olive"]. These all fit the criteria (the last letter matching the first letter of next) and should be pushed into an array.

I've read all the posts on the subject but couldn't find one that seems to fit my problem. I know I'm missing something simple, just can't see it.

fiddle: https://jsfiddle.net/qwL8hq3j/

function validName(array){
var lower = []
for(let i = 0; i < array.length; i++){
lower.push(array[i].toLowerCase());
}
var testA = []
var count = 0;

for(var i = 0; i < lower.length; i++) {
var j = 1;
if(lower[i].charAt(lower[i].length-1) === lower[j].charAt(0)){
testA.push(lower[i]);
j = j + 1;
count = count + 1;
}
}
return count;
}


I put a counter in to make sure the code was cycling and it returns 1, making me conclude that it is only looping through a single time. I've also tried to reconfigure the code a few times but I am just not sure where I'm going wrong.

Answer
var array = ["heehjko", "oient", "ana", "inm", "mii", "dgdgdfg", "Dove"]

var lower = []
for (let i = 0; i < array.length; i++) {
    lower.push(array[i].toLowerCase());
}
console.log(lower)
var testA = []
var count = 0;

for (var i = 0; i < lower.length; i++) {
    var j = 1;
    console.log(lower[i].charAt(lower[i].length - 1))
    console.log(lower[i + 1])
    if (lower[i + 1] != undefined) {
        if (lower[i].charAt(lower[i].length - 1) === lower[i + 1].charAt(0)) {

            testA.push(lower[i + 1]);
        }
    }

}
console.log(testA)