Returning the value of (count of positive / sum of negatives) for an array in JavaScript

Problem

We are required to write a JavaScript function that takes in an array of integers (positives and negatives) and our function should return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.

Using Array.reduce() Method

The most efficient approach uses the reduce() method to iterate through the array once and accumulate both values simultaneously.

const arr = [1, 2, 1, -2, -4, 2, -6, 2, -4, 9];

const posNeg = (arr = []) => {
    const result = arr.reduce((acc, val) => {
        let [count, sum] = acc;
        if (val > 0) {
            count++;
        } else if (val < 0) {
            sum += val;
        }
        return [count, sum];
    }, [0, 0]);
    return result;
};

console.log(posNeg(arr));
[ 6, -16 ]

Using Separate Filter Operations

An alternative approach uses separate filter() operations for clarity, though it requires two array traversals.

const arr = [1, 2, 1, -2, -4, 2, -6, 2, -4, 9];

const posNegSeparate = (arr = []) => {
    const positiveCount = arr.filter(num => num > 0).length;
    const negativeSum = arr.filter(num => num < 0).reduce((sum, num) => sum + num, 0);
    return [positiveCount, negativeSum];
};

console.log(posNegSeparate(arr));
[ 6, -16 ]

Using forEach Loop

A traditional loop approach that's easy to understand and modify.

const arr = [1, 2, 1, -2, -4, 2, -6, 2, -4, 9];

const posNegLoop = (arr = []) => {
    let positiveCount = 0;
    let negativeSum = 0;
    
    arr.forEach(num => {
        if (num > 0) {
            positiveCount++;
        } else if (num < 0) {
            negativeSum += num;
        }
    });
    
    return [positiveCount, negativeSum];
};

console.log(posNegLoop(arr));
[ 6, -16 ]

Comparison

Method Array Traversals Performance Readability
reduce() 1 Best Moderate
filter() 2 Good High
forEach() 1 Best High

Edge Cases

The function handles empty arrays and arrays with only zeros correctly.

console.log(posNeg([]));           // Empty array
console.log(posNeg([0, 0, 0]));    // Only zeros
console.log(posNeg([1, 2, 3]));    // Only positives
console.log(posNeg([-1, -2, -3])); // Only negatives
[ 0, 0 ]
[ 0, 0 ]
[ 3, 0 ]
[ 0, -6 ]

Conclusion

The reduce() method provides the most efficient solution with a single array traversal. For better readability, the forEach() approach is also excellent and equally performant.

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

696 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements