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

如何按指定分组数将数组拆分为子数组?(附示例)

嘿,这个交叉分组的需求我之前也碰到过,给你两个超简便的实现方案,不管用原生ES6+还是Lodash都能轻松搞定,而且完全适配webpack环境👇

原生ES6+实现方法

不需要额外依赖,用原生数组API就能搞定,思路很直观:先初始化对应数量的空分组,然后遍历原数组,把每个元素按索引对分组数取余的规则放到对应的组里,正好符合你要的“依次加入各组后循环”的逻辑。

const crossGroupArray = (arr, groupCount) => {
  // 初始化指定数量的空分组数组
  const groups = Array.from({ length: groupCount }, () => []);
  arr.forEach((item, index) => {
    // 计算当前元素所属的分组索引
    const targetGroupIndex = index % groupCount;
    groups[targetGroupIndex].push(item);
  });
  return groups;
};

// 测试示例
const testArr = [1, 2, 3, 4, 5, 6, 7];
const result = crossGroupArray(testArr, 4);
console.log(result); // 输出:[[1,5], [2,6], [3,7], [4]]
Lodash实现方法

如果你的项目已经引入了Lodash,那可以用它的工具函数进一步简化代码,核心逻辑非常凝练:

import _ from 'lodash';

const crossGroupWithLodash = (arr, groupCount) => {
  // 按索引取余的结果分组,再提取分组后的数组集合
  return _.values(_.groupBy(arr, (_, index) => index % groupCount));
};

// 测试示例
const testArr = [1, 2, 3, 4, 5, 6, 7];
const result = crossGroupWithLodash(testArr, 4);
console.log(result); // 输出:[[1,5], [2,6], [3,7], [4]]

两种方法都能完美满足你的需求,原生方案无依赖更轻量,Lodash方案代码更简洁,看你项目的实际情况选就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:40:32