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 do I transform certain array elements into sub-arrays using JavaScript?

From this javascript array

var test = [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1];

How can I do to get the result as displayed below. Thank you.

test = [[0],1,[0],1,1,1,[0,0],1,[0,0,0,0],1];

I have tried in many ways but I can’t find a solution

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

>Solution :

Here you go:

function group(a) {
    let last = null, res = [];

    for (let x of a)
        if (x === 1)
            res.push(last = x)
        else if (Array.isArray(last))
            last.push(x)
        else
            res.push(last = [x])

    return res
}

let test = [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1];
console.log(group(test))

Can’t help wondering why you need such a thing though…

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