I have been attempting to iterate through an array to determine if any of the values, when compared to all other values in the array using the modulo operation, do not return a 0. Essentially, this process should only return the prime numbers in the array without needing to establish an "isPrime?" function beforehand. It appears to be functioning correctly, except when I include an extra value that I want removed from the array at the end, it does not seem to be 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;
}
I am anticipating the above code to provide variables[2,3,5,7]
, however, it is currently returning variables[2,3,5,7,4]
. Since 4 % 2 = 0
, it should also remove 4 from the array. Where could my mistake be in this implementation?