Search code examples
javascriptarraysmodulo

JS Last value in array is never checked when looped


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?


Solution

  • Since you decrease the array size you should use variables.splice(i--,1).

    You can also use Array::filter() and Array::some() to achieve your goal:

    const variables = [2,3,25,5,7,9,15,14,4];
    
    console.log(...variables.filter(n => !variables.some(val => n % val === 0 & n != val)));