Search code examples
javascriptrowsequencecounting

How can I count "0" sequences in Javascript?


I have this values: [0, 0, 0, 0, 1] and I want to write a code that tells me that there is 1 row of 4 zeroes like in the example above, and if there's 2 rows of 4 zeroes like: [0, 0, 0, 0, 1, 0, 0, 0, 0] henceforth it should say that there are 2 rows of 4 zeroes. How can I do that if you guys could help me??

I haven't tried anything, I only considered counting the zeroes With i index but it just well counts zeroes like there are 4 zeroes, but I want to count how many rows of zeroes are there.


Solution

  • You could search for 1 and store the last position of it. repeat until no more item is found and check if a leftover exists.

    const
        fn = array => {
            const counts = [];
            let l = 0,
                i = array.indexOf(1);
            
            while (i !== -1) {
                counts.push(i - l);
                l = i + 1;
                i = array.indexOf(1, i + 1);
            }
            if (array.length - l > 0) counts.push(array.length - l);
    
            return counts;
        };
    
    
    console.log(...fn([0, 0, 0, 0, 1]));             // 4
    console.log(...fn([0, 0, 0, 0, 1, 0, 0, 0, 0])); // 4 4
    console.log(...fn([0, 0, 0, 0, 1, 0, 0, 0, 0, 1])); // 4 4