javascriptindexofsplice

how to remove specific numbers from a for loop in js


I'm trying too fix the problem I made a for loop that goes from 1 to 100. And I want too remove everything that haves 6 in it.

This is my code

var myarray = [];
for (var i = 1; i <= 100; i++) {
        myarray.push(i);       
    }
console.log(...myarray);

for (var i = 1; i < myarray.length; i++){ 
           if ( myarray.indexOf(6)) {           
               myarray.splice(i, 1); 
             } else {
              ++i
             }
           }
console.log(...myarray);

And this didn't work it will only remove the first 6, could someone help me with this issue?


Solution

  • You could convert each number to a string and check if it contains 6 :

    var myarray = [];
    
    for (let i = 1; i <= 100; i++) {
      if(!i.toString().includes('6')) {
        myarray.push(i);
      } else {
        console.log("skip " + i);
      }
    }
    
    console.log(myarray);

    Note that you could remove the else clause, I've added it to show that we skip the numbers containing a 6.