Open wintran67 opened 11 months ago
To find prime numbers within an array in JavaScript, you can create a function that checks each number in the array for primality. Here's an example: function isPrime(num) { if (num <= 1) return false; // Numbers less than or equal to 1 are not prime
// Check for factors from 2 to the square root of the number for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) return false; // If the number is divisible by any other number, it's not prime } return true; // If no factors other than 1 and itself, it's prime }
// Filter out the numbers which are not prime function findPrimesInArray(arr) { return arr.filter((num) => isPrime(num)); }
// Example usage: const numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]; const primeNumbers = findPrimesInArray(numbers); console.log("Prime numbers in the array:", primeNumbers);
Notes
Please delete this section after reading it
If you have a problem with an error message:
Error output
My Code