如何使用JavaScript将特定数组元素转换为子数组?

huangapple go评论55阅读模式
英文:

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

问题

从这个JavaScript数组中,

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

如何得到如下所示的结果。谢谢。

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

我尝试了很多方法,但找不到解决方案。

英文:

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

答案1

得分: 1

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

英文:

Here you go:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

Can't help wondering why you need such a thing though...

huangapple
  • 本文由 发表于 2023年5月24日 17:27:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定