-4

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

2
  • 1
    Can you show at least one of your 'many ways'? Commented May 24, 2023 at 9:29
  • test = test.reduce((_,$)=>$?[..._,$]:_.at(-1)?.[0]===0?(_.at(-1).push($),_):[..._,[$]],[]); Commented May 24, 2023 at 9:42

1 Answer 1

1

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

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.