How do I transform certain array elements into sub-arrays using JavaScript?

Advertisements

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

>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…

Leave a ReplyCancel reply