JavaScript check if number is prime
Here's a simple way to check if element in an array is a prime number.
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(n) {
if (n<=1) return false
if (n==2) return true
for (var i=2; i<n; i++) {
if (n%i==0) return false
}
return true
}
console.log(array.filter(isPrime))
From this we get
[2, 3, 5, 7, 11, 13]
those numbers that are prime.
Let's go through this step-by-step.
First, we know that negative numbers are excluded. Also number 1 is excluded because by definition a prime is one that is divisible only by one and itself that is not 1.
Number 2 is a prime so let's include that.
Now the main bit (the for
loop). Let's say the number being tested is called n
. Then need to test for number i: 2<i<n-1, whether n%i!=0. If n%i==0 for any i, then n is not a prime.
Lastly, if it passes all tests then return true.
Now for the filter
function of js. We simply pass function isPrime
as callback function to it.
That's it! :)