
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of All Prime Numbers in an Array using JavaScript
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
Advertisements