Find all the prime numbers in the array

How to Find all Prime Numbers in an Array?

If you have an array of numbers, you might want to identify which ones are prime. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. To find out which elements in an array are prime, you can use a function in JavaScript that checks whether a number is divisible by any other number besides 1 and itself.

Method 1: Using a for loop

The simplest method to identify prime numbers is to check each element of the array one by one using a for loop. Here's how you can do it:


function isPrime(num) {
    if(num < 2) return false;
    for(let i = 2; i < num; i++)
        if(num % i === 0) return false;
    return true;
}

let arr = [2, 3, 4, 5, 6, 7, 8, 9, 10];
let primes = [];

for(let i = 0; i < arr.length; i++) {
    if(isPrime(arr[i])) {
        primes.push(arr[i]);
    }
}

console.log(primes); // [2, 3, 5, 7]

In this code, we first define a function called isPrime that checks whether a number is prime or not. We then create an array called arr that contains some numbers. Next, we create an empty array called primes. We use a for loop to iterate through each element of the array arr. For each element, we call the isPrime function to check whether it's prime or not. If it's prime, we add it to the primes array using the push method. Finally, we log the primes array to the console.

Method 2: Using the filter method

An alternative way to find prime numbers in an array is to use the filter method. The filter method creates a new array with all elements that pass the test implemented by the provided function. Here's how you can use it:


function isPrime(num) {
    if(num < 2) return false;
    for(let i = 2; i < num; i++)
        if(num % i === 0) return false;
    return true;
}

let arr = [2, 3, 4, 5, 6, 7, 8, 9, 10];

let primes = arr.filter(isPrime);

console.log(primes); // [2, 3, 5, 7]

In this code, we define the same isPrime function as before. We then create an array called arr that contains some numbers. We use the filter method on this array and pass in the isPrime function as the callback function. The filter method creates a new array called primes that contains only the elements of the original array that pass the test implemented by the callback function. Finally, we log the primes array to the console.

So, these are two methods that you can use to find all the prime numbers in an array. You can choose which one to use based on your preference and the requirements of your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe