英文:
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...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论