Counting the clusters of positive numbers - JavaScript Arrays

Let's say, we have an array of numbers like this ?

const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0];

We are required to write a JavaScript function that counts the consecutive groups of non-negative (positives and 0) numbers in the array.

Like here we have consecutive non-negatives from index 3 to 3 (only one element, but still a cluster) which forms one group and then from index 9 to end of array forms the second group.

Therefore, for this array, the function should return 2.

How It Works

The algorithm identifies the end of each non-negative cluster by checking if the current element is non-negative and the next element is either negative or doesn't exist (end of array).

Example

Following is the code ?

const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0];

const positiveClusters = arr => {
    return arr.reduce((acc, val, ind) => {
        if(val >= 0 && (arr[ind+1] 

Output

This will produce the following output in console ?

2

Alternative Approach Using For Loop

Here's another way to solve the same problem using a traditional for loop:

const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0];

const countClusters = (arr) => {
    let clusters = 0;
    let inCluster = false;
    
    for (let i = 0; i = 0) {
            if (!inCluster) {
                clusters++;
                inCluster = true;
            }
        } else {
            inCluster = false;
        }
    }
    
    return clusters;
};

console.log(countClusters(arr));
2

Testing with Different Arrays

// Test with different arrays
console.log(positiveClusters([1, 2, 3]));           // 1 cluster
console.log(positiveClusters([-1, -2, -3]));        // 0 clusters  
console.log(positiveClusters([1, -1, 2, -2, 3]));   // 3 clusters
console.log(positiveClusters([0, 0, -1, 0, 0]));    // 2 clusters
1
0
3
2

Conclusion

The reduce method provides an elegant solution for counting non-negative clusters by detecting cluster endpoints. Both approaches work effectively, with the for loop being more readable for beginners.

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

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements