Grouping of same kind of numbers in JavaScript

We have an array of numbers with both negative and non-negative values. Our goal is to count consecutive groups of non-negative numbers (positives and zeros) in the array.

const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0];
console.log("Array:", arr);
Array: [-1, -2, -1, 0, -1, -2, -1, -2, -1, 0, 1, 0]

In this array, we need to identify consecutive groups of non-negative numbers. Looking at the array:

  • Index 3: single element 0 forms one group
  • Indices 9-11: elements 0, 1, 0 form another group

So the function should return 2 for this array.

Solution Using Array.reduce()

We can solve this by iterating through the array and counting groups that end when we reach the last non-negative number before a negative number or the array end.

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] < 0 || typeof arr[ind+1] === 'undefined')){
            acc++;
        };
        return acc;
    }, 0);
};

console.log("Number of non-negative clusters:", positiveClusters(arr));
Number of non-negative clusters: 2

How It Works

The algorithm works by:

  1. Using reduce() to iterate through each element with its index
  2. Checking if the current element is non-negative (val >= 0)
  3. Checking if it's the end of a cluster by looking at the next element
  4. A cluster ends when the next element is negative or we've reached the array end
  5. Incrementing the counter each time we find the end of a cluster

Alternative Approach Using For Loop

Here's a more readable solution using a traditional for loop:

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

function countNonNegativeClusters(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("Clusters found:", countNonNegativeClusters(arr));
Clusters found: 2

Testing With Different Arrays

Let's test both approaches with different array configurations:

// Test cases
const testCases = [
    [1, 2, 3, -1, -2, 4, 5],      // 2 clusters
    [-1, -2, -3],                 // 0 clusters  
    [1, 2, 3, 4],                 // 1 cluster
    [0, -1, 0, -1, 0]             // 3 clusters
];

testCases.forEach((testArr, index) => {
    console.log(`Test ${index + 1}: [${testArr.join(', ')}]`);
    console.log(`Clusters: ${positiveClusters(testArr)}`);
});
Test 1: [1, 2, 3, -1, -2, 4, 5]
Clusters: 2
Test 2: [-1, -2, -3]
Clusters: 0
Test 3: [1, 2, 3, 4]
Clusters: 1
Test 4: [0, -1, 0, -1, 0]
Clusters: 3

Conclusion

The reduce approach efficiently counts consecutive groups by identifying cluster endpoints. Both solutions handle edge cases like empty arrays and arrays with only negative numbers correctly.

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

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements