discussions
discussions copied to clipboard
how to find a prime number in a array in java script
Notes
- If you have a question about the NodeSchool organization: Please open an issue in nodeschool/organizers
- If you want to improve or contribute to workshoppers: Please open an issue in workshopper/org
- Did you see the guide for questions? https://github.com/nodeschool/discussions#when-you-have-a-problem
Please delete this section after reading it
If you have a problem with an error message:
- node version: <run "node -v" in you terminal and replace this>
- npm version: <run "npm -v" in you terminal and replace this>
- os: windows 7/windows 10/mac/linux
Error output
// copy your error output here
My Code
// copy your code here
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);