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

Split an array when meets a certain number?

Hello I need to return count of chunks in given array of numbers.

Chunk can be defined assequence of one or more numbers separated by one or more zeroes.

Example: array [5, 4, 0, 0, -1, 0, 2, 0, 0] contains 3 chunks

so the answer should be 3 since the array can be split into three chunks.

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

Can you help me with the solution to this one?

Ive looped through the array but dont know how to deal with the multiple zeros.

>Solution :

You could add a flag for keeping track of counting the actual chunk and rest it only by fing a zero.

let data = [5, 4, 0, 0, -1, 0, 2, 0, 0],
    count = 0,
    lastCount = false;

for (const value of data) {
    if (value === 0) {
        lastCount = false;
        continue;
    }
    if (!lastCount) {
        count++;
        lastCount = true;
    }
}

console.log(count);
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