- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Non-composite numbers sum in an array in 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.
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
- Related Articles
- Count and Sum of composite elements in an array in C++
- Sum of all prime numbers in an array - JavaScript
- Product of all the Composite Numbers in an array in C++
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- Go through an array and sum only numbers JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Squared and square rooted sum of numbers of an array in JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- Taking the absolute sum of Array of Numbers in JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Difference between numbers and string numbers present in an array in JavaScript
- Sum of distinct elements of an array in JavaScript
- Finding sum of a range in an array JavaScript

Advertisements