Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I can split an array into different chunks depending on a certain number of zeros that exist in the array?

suppose that I have the following array:

In:[0,0,0,0,0,12,34,45,34,65,76,33,66,76,44,32,99,0,0,0,0,0,43,23,54,33,44,22,66,0,0,0,0,0]

I want to split the main array into several sub-array depending on a given condition, that is if there are 5 zero values in the array split the array into subarrays while discarding the zero value in the main array.

The output array should be as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

out:[[12,34,45,34,65,76,33,66,76,44,32,99],[43,23,54,33,44,22,66]]

How I can manage to do that in javascript? Your help is much appreciated.

>Solution :

You could use a traditional for loop that keeps track of the last index no consecutive zeroes were found and the number of consecutive zeroes:

const input = [0,0,0,0,0,12,34,45,34,65,76,33,66,76,44,32,99,0,0,0,0,0,43,23,54,33,44,22,66,0,0,0,0,0]

const output = [];

for (let i = 0, j = 0, c = 0; i < input.length; i++) {
    if (input[i] === 0) c++; // another zero, add to counter
    else c = 0;              // reset counter if no zero
    
    if (c === 5) {           // 5 consecutive zeroes
        const slice = input.slice(j, i + 1 - 5); // get our slice
        if (slice.length) output.push(slice);    // only add if slice is not empty
        j = i + 1;           // store ending index at which we found this slice
        c = 0;               // reset counter
    }
}

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading