Search code examples
javascriptarraysloopsnested-loops

JavaScript - Cannot get 2 arrays combined in 1 empty array using a nested loop


I am new here and I am also just been coding for a few months. I am stuck with an example of testing a nested loop and I cannot get this solved.

I am trying to get 2 arrays with strings to be added to an empty array. I know how to do this with array methods( or is it functions), but I was trying to see if I can add each item into this empty array by comparing them both against each other. If they are not the same name, add to the array.

But it is stuck in an infinite loop. It will keep adding items to the empty array that are 'undefined'. So it is basically doing the job, but then won't stop adding items in the array.

Here is my code:

const completedComics = ['Creepshow', 'X-O Manowar', 'Saga']
const completedComics2 = ['Descender', 'Ascender', 'The Last Ronin']
let totalCompletion = []

for (let c = 0; c < completedComics.length; c++){
    for(let c2 = 0; c2 < completedComics2.length; c++){
        if (completedComics[c] != completedComics2[c2]){
            totalCompletion.push(completedComics[c])
        }
    }
}
console.log(totalCompletion.join(", "))

I am trying to get a list of comic names from the first array, and a list of items from another, to be added together into the 'totalCompletion' array.

I tried adding an else statement to add them and the if statement to not do anything if they are equals (===) to each other but that just adds the items in an infinite loop instead of 'undefined'. I have also tried to move things around, remove the index from the variable calls in the 'if' statement but no matter what happens, if cannot get past that inner loop.

What I am trying to do is, with a nested loop, to have both 'completedComics' and 'completedComics2' index items be all in one place, the 'totalCompletion' array.

This is what I would want as the result:

console.log(totalCompletion.join(", "))

['Creepshow', 'X-O Manowar', 'Saga', 'Descender', 'Ascender', 'The Last Ronin']

Solution

  • In your second loop, you need to increment c2, not c.

    for (let c = 0; c < completedComics.length; c++){
        for(let c2 = 0; c2 < completedComics2.length; c2++){ // <-- Here, replace c by c2
            if (completedComics[c] != completedComics2[c2]){
                totalCompletion.push(completedComics[c])
            }
        }
    }