Positive integer square array JavaScript

In JavaScript, we often need to filter arrays to extract specific types of numbers and perform operations on them. This example demonstrates how to find positive integers in an array and return the sum of their squares.

Problem Statement

Given an array containing various numbers (positive, negative, decimals, and integers), we need to write a function that returns the sum of squares of all positive integers only.

Solution

We'll use the reduce() method to iterate through the array and accumulate the sum of squares for positive integers:

const arr = [1, -4, 6.1, 0.1, 2.6, 5, -2, 1.9, 6, 8.75, -7, 5];

const squareSum = (arr) => {
    return arr.reduce((acc, val) => {
        // First condition checks for positivity, second for wholeness
        if (val > 0 && val % 1 === 0) {
            acc += val * val;
        }
        return acc;
    }, 0);
}

console.log(squareSum(arr));
87

How It Works

The function checks two conditions for each array element:

  • val > 0 - Ensures the number is positive
  • val % 1 === 0 - Checks if the number is an integer (no decimal remainder)

From our example array, the positive integers are: 1, 5, 6, 5. Their squares are: 1, 25, 36, 25. The sum is 1 + 25 + 36 + 25 = 87.

Alternative Approach Using Filter and Map

Here's another way to solve the same problem using filter() and map():

const arr = [1, -4, 6.1, 0.1, 2.6, 5, -2, 1.9, 6, 8.75, -7, 5];

const squareSumAlternative = (arr) => {
    return arr
        .filter(val => val > 0 && val % 1 === 0)  // Filter positive integers
        .map(val => val * val)                     // Square each value
        .reduce((acc, val) => acc + val, 0);       // Sum all squares
}

console.log(squareSumAlternative(arr));
87

Conclusion

Both approaches effectively filter positive integers and calculate the sum of their squares. The first method is more efficient as it processes the array in a single pass, while the second is more readable by separating the filtering, mapping, and reducing operations.

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

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements