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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
996