skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. You could 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search