Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to find prime numbers in an array in javascript

// how to find prime numbers in an array in javascript
let num = [-1,-2,-3,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
let result = [];
function isPrime(num) {
  if(num < 2) return false;

  for (let k = 2; k < num; k++){
    if(num % k == 0){
      return false;
    }
  }
  return true;
}
num.forEach(function (element) {
  const item = isPrime(element);
  if (item) {
    result.push(element);
  }
});
console.log(result); // [ 2, 3, 5, 7, 11, 13, 17, 19]
 
PREVIOUS NEXT
Tagged: #find #prime #numbers #array #javascript
ADD COMMENT
Topic
Name
3+9 =