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

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

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

问题

从这个JavaScript数组中,

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

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

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

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

英文:

From this javascript array

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

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

  1. function group(a) {
  2. let last = null, res = [];
  3. for (let x of a)
  4. if (x === 1)
  5. res.push(last = x)
  6. else if (Array.isArray(last))
  7. last.push(x)
  8. else
  9. res.push(last = [x])
  10. return res
  11. }
  12. let test = [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1];
  13. 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 -->

  1. function group(a) {
  2. let last = null, res = [];
  3. for (let x of a)
  4. if (x === 1)
  5. res.push(last = x)
  6. else if (Array.isArray(last))
  7. last.push(x)
  8. else
  9. res.push(last = [x])
  10. return res
  11. }
  12. let test = [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1];
  13. 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:

确定