Sum of all positives present in an array in JavaScript

We are required to write a JavaScript function that takes in an array of numbers (positive and negative). Our function should calculate and return the sum of all the positive numbers present in the array.

Method 1: Using reduce() with Helper Function

This approach uses a helper function to check if a number is positive and reduce() to accumulate the sum:

const arr = [5, -5, -3, -5, -7, -8, 1, 9];

const sumPositives = (arr = []) => {
    const isPositive = num => typeof num === 'number' && num > 0;
    const res = arr.reduce((acc, val) => {
        if(isPositive(val)){
            acc += val;
        }
        return acc;
    }, 0);
    return res;
};

console.log(sumPositives(arr));
15

Method 2: Using filter() and reduce()

We can first filter positive numbers, then sum them:

const arr = [5, -5, -3, -5, -7, -8, 1, 9];

const sumPositives = (arr = []) => {
    return arr.filter(num => num > 0)
              .reduce((sum, num) => sum + num, 0);
};

console.log(sumPositives(arr));
15

Method 3: Using for...of Loop

A simple loop approach for better readability:

const arr = [5, -5, -3, -5, -7, -8, 1, 9];

const sumPositives = (arr = []) => {
    let sum = 0;
    for (let num of arr) {
        if (num > 0) {
            sum += num;
        }
    }
    return sum;
};

console.log(sumPositives(arr));
15

Handling Edge Cases

Let's test our function with different scenarios:

const sumPositives = (arr = []) => {
    return arr.filter(num => num > 0)
              .reduce((sum, num) => sum + num, 0);
};

console.log(sumPositives([]));           // Empty array
console.log(sumPositives([-1, -2, -3])); // All negatives
console.log(sumPositives([0, 1, 2]));    // Including zero
console.log(sumPositives([1.5, 2.7, -1.2])); // Decimals
0
0
3
4.2

Performance Comparison

Method Readability Performance Memory Usage
reduce() with helper Good Good Low
filter() + reduce() Excellent Moderate Higher
for...of loop Excellent Best Low

Conclusion

The filter() + reduce() method offers the best readability, while the for...of loop provides optimal performance. Choose based on your specific needs and coding style preferences.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements