Nested loops

Hi, I am trying to do a simple nested for loop which checks characters in a variable and compares them with characters in an array to see if any characters are the same. If they are the same, I want to .push() these characters into an empty array and then console.log the outcome using .toUpperCase(). This is what i have done so far and seem to be having trouble. It seems like it could be easy for someone to figure out where I have went wrong but nested loops aren’t my strong point. Any help would be greatly appreciated. Thanks.

const sentence = "My name is Ryan Porter";
const myArray = ["My name is Ryan Porter"];
const newEmptyArray = [];

for(i = 0; i<sentence; i++) {
    for(j = 0; j<myArray; j++) {
        if(sentence[i] === myArray[j]) {
            newEmptyArray.push(sentence[i]);
        }
    }
}
console.log(newEmptyArray.toUpperCase());

Hi,
try these consoles at the end of your code. Maybe that solves the major misunderstanding already?

console.log(sentence[0], myArray[0]);
console.log(sentence[0], myArray[0][0]);
1 Like

@mirja_t is right, or within the loop to get an even more detailed pictured:

const sentence = "My name is Ryan Porter";
const myArray = ["My name is Ryan Porter"];
const newEmptyArray = [];


for(i = 0; i<sentence; i++) {
    for(j = 0; j<myArray; j++) {
        console.log(i, j, sentence[i], myArray[j]);
        if(sentence[i] === myArray[j]) {
            newEmptyArray.push(sentence[i]);
        }
    }
}
console.log(newEmptyArray);

but this also highlights that your loops aren’t working, seems to be a problem with your loop conditions

2 Likes

sentence is a string and myArray is an array. So you are comparing sentence[i] with myArray[j]. One problem is that myArray only has one element:

const sentence = "My name is Ryan Porter";
const myArray = ["My name is Ryan Porter"];

It would be easier to compare a string with a string (or an array with an array but then each element would need to be a separate one letter string). Your stopping conditions in the for loops are also not correct:

for(i = 0; i<sentence; i++) {
    for(j = 0; j<myArray; j++) {
    // logic
   }
}

You commonly stop this kind of loop using the .length method on the string or array. So you could use sentence.length instead to get an number of the string length and use that.

Also make sure to declare i and j using let (or var - but let is preferable) when you set up the for-loop. i = 0 will cause some problems and is not allowed in strict JS mode.