how to remove specific numbers from a for loop in js

112 Views Asked by At

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?

2

There are 2 best solutions below

3
Tom On BEST ANSWER

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.

0
Roko C. Buljan On

Use Array.prototype.filter() (to create a new, fitered Array) and String.prototype.includes() (to filter out integers which string representation includes the character "6")

const myarray = Array.from(Array(100), (_, i) => i+1);
const result = myarray.filter(n => !`${n}`.includes("6"));

console.log(result);