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

如何在JavaScript中按连续状态拆分数组为多个子数组?

按连续状态拆分JavaScript数组

要实现将数组按连续的status字段拆分为子数组,只需要一次遍历数组即可完成,时间复杂度为O(n),处理1000条数据完全没有性能压力。以下是两种高效的实现方式:

方式一:使用Array.reduce(简洁写法)

reduce方法可以在遍历过程中直接维护分组结果,代码更紧凑:

const main_array = [
  {'date': '2023-10-02 00:01:00', 'status': 'on'},
  {'date': '2023-10-02 00:02:00', 'status': 'on'},
  {'date': '2023-10-02 00:03:00', 'status': 'off'},
  {'date': '2023-10-02 00:04:00', 'status': 'off'},
  {'date': '2023-10-02 00:05:00', 'status': 'off'},
  {'date': '2023-10-02 00:06:00', 'status': 'on'},
  {'date': '2023-10-02 00:07:00', 'status': 'on'},
  {'date': '2023-10-02 00:08:00', 'status': 'on'},
  {'date': '2023-10-02 00:09:00', 'status': 'off'},
  {'date': '2023-10-02 00:10:00', 'status': 'off'}
];

const groupedArrays = main_array.reduce((acc, currentItem) => {
  // 若结果为空,或当前元素状态与最后一个分组的最后元素状态不同,则新建分组
  if (!acc.length || currentItem.status !== acc.at(-1).at(-1).status) {
    acc.push([currentItem]);
  } else {
    // 否则将当前元素加入最后一个分组
    acc.at(-1).push(currentItem);
  }
  return acc;
}, []);

// 输出结果:[[...on组], [...off组], [...on组], [...off组]]
console.log(groupedArrays);

方式二:使用普通for循环(直观写法)

如果更习惯命令式编程,普通for循环的逻辑更直白,性能和reduce相当:

const main_array = [
  {'date': '2023-10-02 00:01:00', 'status': 'on'},
  {'date': '2023-10-02 00:02:00', 'status': 'on'},
  {'date': '2023-10-02 00:03:00', 'status': 'off'},
  {'date': '2023-10-02 00:04:00', 'status': 'off'},
  {'date': '2023-10-02 00:05:00', 'status': 'off'},
  {'date': '2023-10-02 00:06:00', 'status': 'on'},
  {'date': '2023-10-02 00:07:00', 'status': 'on'},
  {'date': '2023-10-02 00:08:00', 'status': 'on'},
  {'date': '2023-10-02 00:09:00', 'status': 'off'},
  {'date': '2023-10-02 00:10:00', 'status': 'off'}
];

const groupedArrays = [];

// 处理空数组的边界情况
if (main_array.length === 0) {
  console.log(groupedArrays);
}

// 初始化第一个分组
let currentGroup = [main_array[0]];
groupedArrays.push(currentGroup);

// 从第二个元素开始遍历
for (let i = 1; i < main_array.length; i++) {
  const currentItem = main_array[i];
  // 状态一致则加入当前分组
  if (currentItem.status === currentGroup.at(-1).status) {
    currentGroup.push(currentItem);
  } else {
    // 状态不一致则新建分组
    currentGroup = [currentItem];
    groupedArrays.push(currentGroup);
  }
}

// 输出结果:[[...on组], [...off组], [...on组], [...off组]]
console.log(groupedArrays);

核心逻辑说明

两种方法的核心都是一次遍历数组,只需要维护当前分组和结果数组:

  • 每次对比当前元素的status与当前分组最后一个元素的status
  • 状态相同则将元素加入当前分组,不同则创建新分组并加入结果数组

这种实现方式不会产生额外的性能开销,即使处理上万条数据也能轻松应对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:16:30