skip to Main Content

I am trying to loop through an array to check whether none of the values when compared with all of the remaining values in the array return a 0 after using the modulo operation.

In effect, this should only return the primes in the array without first establishing a "isPrime?" function. It currently seems to work unless I add an errant value I want spliced at the end of the array.. that one doesn’t seem to get checked?

function ModuloPrimes(variables) {
  
  const variables = [2,3,25,5,7,9,15,14,4]

  variables.forEach(val => {                
    for(let i = 0; i < variables.length; i++){
      if(variables[i] % val === 0 & variables[i] != val){
      variables.splice(i,1)
      ++i
  }
  }
  })
    return variables
}

What I expect the above code to return is variables[2,3,5,7] but currently it returns variables[2,3,5,7,4] and since 4 % 2 = 0 it should also splice 4. Where am I going wrong with this?

2

Answers


  1. Array::forEach and other array methods use Array::length at the START of their execution to iterate elements and DON’T check it again. So any extra items you put into an array won’t be iterated. Moreover if you remove items from an array, the will be iterated anyway as undefined.

    const variables = [2,3,25,5,7,9,15,14,4];
    
    console.log(...variables.filter(n => !variables.some(val => n % val === 0 & n != val)));
    Login or Signup to reply.
  2. Wrong logic: when variables.splice(i,1) the array gets decreased in length so you should check the loop i again, not jump over; simply replace ++i with --i will solve the problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search