You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用正则表达式从一维数组生成连续零的二维数组

提取连续零组为二维数组(无正则实现)

我是新手,现有一维数组:

[1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6]

希望得到如下二维数组:

[[0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]

已有一个用正则结合split的实现,但返回的是零字符串,现在需要不使用正则,且返回包含数字0的二维数组的方案。原代码如下:

function zeroGroups(arr){
    const allZerosGroups = arr
      .map(item => item !== 0 ? '-' : 0)
      .join('')
      .split(/[^0]/)
      .filter(item => item.length !== 0)
      
    return allZerosGroups
}
console.log(zeroGroups([1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6])) // [ '0000', '0000000' ]

无正则实现方案

通过遍历数组跟踪连续零分组的方式实现,直接生成数字0组成的二维数组:

function zeroGroups(arr) {
  const result = [];
  let currentZeroGroup = null;

  for (const num of arr) {
    if (num === 0) {
      // 遇到0时,若当前无分组则新建,否则追加0到当前分组
      if (!currentZeroGroup) {
        currentZeroGroup = [];
      }
      currentZeroGroup.push(0);
    } else {
      // 遇到非0时,若当前有未保存的分组则存入结果,重置分组
      if (currentZeroGroup) {
        result.push(currentZeroGroup);
        currentZeroGroup = null;
      }
    }
  }

  // 处理数组末尾可能剩余的零分组
  if (currentZeroGroup) {
    result.push(currentZeroGroup);
  }

  return result;
}

console.log(zeroGroups([1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6]));
// 输出: [[0,0,0,0],[0,0,0,0,0,0,0]]

逻辑说明

  1. 初始化结果数组result和临时变量currentZeroGroup用于跟踪当前正在收集的零分组
  2. 遍历原数组每个元素:
    • 元素为0时,若没有正在收集的分组则创建新数组,将0加入当前分组
    • 元素非0时,若存在未保存的零分组,将其存入结果数组并重置临时变量
  3. 遍历结束后,检查是否还有未存入结果的零分组(比如数组末尾是连续0的情况),若有则补充到结果中

内容的提问来源于stack exchange,提问作者chernets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:35:03