Sum of all prime numbers in an array - JavaScript

We are required to write a JavaScript function that takes in an array of numbers and returns the sum of all the prime numbers present in the array.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11 are prime numbers.

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:

43 + 5 + 71 + 877 = 996

Solution

We'll create two functions: one to check if a number is prime, and another to calculate the sum of all prime numbers in the array.

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  {
    let sum = 0;
    for (let i = 0; i 

996

How It Works

The isPrime function checks if a number is prime by:

  • Returning false for 1 (not considered prime)
  • Returning true for 2 (the only even prime)
  • Testing divisibility from 2 to n-1 for other numbers

The primeSum function iterates through the array, checks each number for primality, and adds prime numbers to the running sum.

Optimized Version

We can optimize the prime checking by only testing up to the square root of the number:

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

const isPrimeOptimized = n => {
    if (n  {
    return arr.filter(isPrimeOptimized).reduce((sum, num) => sum + num, 0);
};

console.log(primeSumOptimized(arr));
996

Conclusion

To sum prime numbers in an array, create a helper function to check primality and iterate through the array adding only prime numbers. The optimized version uses mathematical properties to reduce computation time significantly.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements