| Viewed 348 times

How to Filter Primes from an Array in Javascript


I need a function that takes an array and returns a new array containing only prime numbers.

1 Answer
Mohammad Qandeel
Answered
20

This function will take an array and returns a new array containing only prime numbers.

const filterPrimes = array => {
 const isPrime = n => {
  for (let i = 2; i < n; i++) if (n % i === 0) return false;
  return n > 1;
 }
 return array.filter(number => isPrime(number));
}

Example

filterPrimes([112,11]) //[11]

 


Related Questions