Count groups of negatives numbers in JavaScript

We have an array of numbers like this:

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

Let's say, we are required to write a JavaScript function that counts the consecutive groups of negative numbers in the array.

Like here we have consecutive negatives from index 0 to 2 which forms one group and then from 4 to 8 forms the second group.

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

Understanding the Problem

A group of consecutive negative numbers is defined as:

  • One or more negative numbers appearing next to each other
  • Separated by zero or positive numbers
  • Each group is counted as one unit regardless of its size

Solution Using Array.reduce()

The approach is to iterate through the array and count groups by detecting when a negative number is followed by a non-negative number (indicating the end of a group):

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

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

console.log(countNegativeGroup(arr));
2

How It Works

The function uses Array.reduce() with the following logic:

  • val - checks if current element is negative
  • arr[ind+1] >= 0 - checks if next element is zero or positive
  • When both conditions are true, we've found the end of a negative group
  • The accumulator acc keeps count of groups found

Alternative Solution Using For Loop

const countNegativeGroupsLoop = (arr) => {
    let count = 0;
    let inNegativeGroup = false;
    
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < 0) {
            inNegativeGroup = true;
        } else if (inNegativeGroup) {
            count++;
            inNegativeGroup = false;
        }
    }
    
    // Handle case where array ends with negative numbers
    if (inNegativeGroup) {
        count++;
    }
    
    return count;
};

const testArray = [-1, -2, -3, 1, -4, -5, 0, -6];
console.log(countNegativeGroupsLoop(testArray));
3

Testing with Different Arrays

// Test cases
console.log(countNegativeGroup([-1, -2, 1, -3]));     // 2 groups
console.log(countNegativeGroup([1, 2, 3]));           // 0 groups  
console.log(countNegativeGroup([-1, -2, -3]));        // 1 group
console.log(countNegativeGroup([]));                  // 0 groups
2
0
1
0

Conclusion

The reduce() method provides an elegant solution for counting consecutive negative groups. The key insight is detecting group endings by checking when a negative number is followed by a non-negative one.

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

460 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements