Home > front end >  How I can split an array into different chunks depending on a certain number of zeros that exist in
How I can split an array into different chunks depending on a certain number of zeros that exist in

Time:10-31

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:

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.

CodePudding user response:

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);

  • Related