Was it helpful?

Question

Sum of all prime numbers in an array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers.

The function should return the sum of all the prime numbers present in the array.

Let’s say the following is our array −

const arr = [43, 6, 6, 5, 54, 81, 71, 56, 8, 877, 4, 4];

The function should sum the prime numbers i.e.

43 + 5 + 71 + 877 = 996

Example

Following is the code −

const arr = [43, 6, 6, 5, 54, 81, 71, 56, 8, 877, 4, 4];
const isPrime = n => {
   if (n===1){
      return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const primeSum = arr => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      if(!isPrime(arr[i])){
         continue;
      };
      sum += arr[i];
   };
   return sum;
};
console.log(primeSum(arr));

Output

This will produce the following output in console −

996
raja
Published on 30-Sep-2020 17:02:29
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top