-3

I'm working on a React project and need help with a function that prints prime numbers from an array to the console. Here's the code I've tried so far:

// My code snippet
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function printPrimes(arr) {
  // Code that I need help with
}

printPrimes(numbers);

I'm looking for a React function that, given an array of numbers, prints the prime numbers to the console. For the given example array numbers, the expected output would be 2, 3, 5, 7. I'm unsure how to implement the primality check and iterate over the array efficiently. Can anyone guide me in the right direction and provide a solution?

I've researched algorithms for checking prime numbers, but I'm having trouble integrating them into my React function. Any help or suggestions would be greatly appreciated. Thank you!

Luis Colon
  • 27
  • 1
  • 9
  • 3
    Have you written any code to check for primes? – Unmitigated Mar 23 '23 at 23:44
  • `primes` is an empty array. Why do you think your code should print anything other than an empty string? – Barmar Mar 23 '23 at 23:45
  • Does this answer your question? [Check Number prime in JavaScript](https://stackoverflow.com/q/40200089/283366) – Phil Mar 23 '23 at 23:47
  • im trying o save the prime numbers inside the primes variable. I also updated with what i tried – Luis Colon Mar 23 '23 at 23:49
  • 1
    You declare an `isPrime()` function but you never use it; which, by the way, is a very inefficient implementation. You declare also declare a `primes` variable but never update it. There is some basic understanding that is missing here. We are not entirely sure where to guide you. You need to make a better initial attempt yourself. – Stephen Quan Mar 23 '23 at 23:56

2 Answers2

0
let numbers = [...Array(100).keys()];
let primes = [];

for (let i = 2; i < numbers.length; i++) {
  let isPrime = true;
  
  for (let j = 2; j < i; j++) {
    if (i % j === 0) {
      isPrime = false;
      break;
    }
  }
  
  if (isPrime) {
    primes.push(i);
    console.log(i);
  }
}

Yo, so basically this code goes through every number in the numbers array, and for each number it checks if it's a prime by dividing it by all the numbers between 2 and itself. If it's a prime, it gets added to the primes array and printed out to the console.

Hope that helps, man! Lemme know if you got any other questions or whatever.

IsraelCena
  • 29
  • 1
  • 6
0
var numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers = numbers.filter((number) => {
  for (var i = 2; i <= Math.sqrt(number); i++) {
    if (number % i === 0) return false;
  }
  return true;
});

console.log(numbers);