Search code examples
javascriptarraysfor-loopforeachfor-of-loop

How to loop through 2 arrays as arguments with for, for of, or forEach


I am somewhat new to Javascript so I'll try my best to explain this properly. I'm using vanilla JS on the fizz buzz loop, but I'm trying to do it slightly differently, I think.

I've put both sets of numbers in 2 separate arrays, and successfully did it with a for loop by counting up to 20, but I didn't use the arrays to do it. However, I want to use the variables passed as arguments to check if the values are true so the appropriate response can be printed, either fizz, buzz, or fizzbuzz.

My code for the for loop is:

const fizz = [3, 6, 9, 12, 15, 18];
const buzz = [5, 10, 15, 20];

for (let i = 1; i <= 20; i++){
    if(i % 3 === 0 && i % 5 === 0) {
        console.log(i + " fizz buzz");
    } else if(i % 3 === 0){
       console.log(i + " fizz");
    } else if(i % 5 === 0) {
    console.log(i + " buzz");
    } else {
        console.log(i);
    }
}
.as-console-wrapper {max-height: 100%!important;top:0}

As I said, that runs successfully.

I did edit the for loop with the fizz & buzz variables, with no success. I tried using index & indexOf, but I'm not sure how to code that.

I also used for of & forEach, but I'm struggling on how to code those as well.

I know it's messy, but how I coded my forEach method looks like this:

fizz.forEach(function(value) {
     if (i === fizz.indexOf[value]) {
        console.log(value);
         i++;
     }
});

Ultimately my questions with all of this is - how do I pass those arrays as arguments to be looped through and checked if their values are true or not? And, which is the best way of doing it?


Solution

  • You can test if the number you're iterating is inside of any of the arrays with the function some. For example,

    const fizz = [3, 6, 9, 12, 15, 18];
    const buzz = [5, 10, 15, 20];
    
    for(let i = 1; i <= 20; i++){
        const isFizz = fizz.some(f => f === i);
        const isBuzz = buzz.some(b => b == i);
        if(isFizz && isBuzz){
            console.log(i + " fizz buzz");
        } else if(isFizz){
            console.log(i + " fizz");
        } else if(isBuzz){
            console.log(i + " buzz");
        } else {
            console.log(i);
        }
    }
    

    *Note: The performance of the overall algorithm is greater than linear, as some() iterates over the arrays and is inside a for loop. Another approach is make isFizz = n => n%3 === 0 and isBuzz = n => n%5 === 0, and get linear time complexity.