Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print an array which is divisible by two numbers?

I found myself a problem. I want to print an array from number 0 to 100.
if the number is divisible by 3, I want to print flip.
if the number is divisible by 5, I want to print flop.
for example the array should be [0,1,2,’flip’,4,’flop’,’flip,……..,’flop’].
How to do this in JS?
So far I have done this but it doesn’t print the whole array.

function wow() {
  var arr = []
  for (let i = 0; i <= 100; i++) {
    if(i!=0){
      if(i%3===0){
        i='flip'
        arr.push(i)
      }
      if(i%5===0){
        i='flop'
        arr.push(i)
      }
    }
    arr.push(i)
  }
  console.log(arr)
}
wow()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re changing the variable i within the for loop which you shouldn’t be doing. Try using a temp variable for determining what gets pushed to your array.

Also, if a number is divisible by 3 AND 5 then the latter (flop) takes precedent, is that what you expect to happen?

function wow() {
  var arr = []
  for (let i = 0; i <= 100; i++) {
    let temp = i;
    if (i != 0) {


      if (i % 3 === 0) {
        temp = 'flip'
      }
      if (i % 5 === 0) {
        temp = 'flop'
      }
    }
    arr.push(temp)

  }
  console.log(arr);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading