Finding clusters of consecutive negative integers in JavaScript

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 negative numbers in the array.

Understanding the Problem

In the example array [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0], we have:

  • First cluster: [-1,-2,-1] (positions 0-2)
  • Second cluster: [-1,-2,-1,-2,-1] (positions 4-8)

The function should return 2 since there are two separate groups of consecutive negative numbers.

Solution

The algorithm uses the reduce() method to iterate through the array and increment a counter whenever we find the end of a negative cluster:

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

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

console.log(countClusters(arr));

Output

2

How It Works

The function works by checking each element:

  1. Current element is negative: val
  2. Next element is non-negative: arr[ind+1] >= 0

When both conditions are true, we've found the end of a negative cluster, so we increment the counter.

Alternative Approach

Here's another solution that tracks whether we're currently inside a negative cluster:

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

const countClustersAlt = arr => {
    let clusters = 0;
    let inCluster = false;
    
    for(let i = 0; i < arr.length; i++) {
        if(arr[i] < 0) {
            if(!inCluster) {
                clusters++;
                inCluster = true;
            }
        } else {
            inCluster = false;
        }
    }
    return clusters;
};

console.log(countClustersAlt(arr));

Output

2

Edge Cases

// Empty array
console.log(countClusters([]));  // 0

// No negative numbers
console.log(countClusters([1, 2, 3]));  // 0

// All negative numbers
console.log(countClusters([-1, -2, -3]));  // 1

// Single negative number
console.log(countClusters([1, -1, 2]));  // 1

Output

0
0
1
1

Conclusion

The reduce-based solution efficiently counts consecutive negative clusters by detecting cluster endpoints. Both approaches handle edge cases correctly and provide reliable cluster counting functionality.

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

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements