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

如何将对象数组划分为指定数量的分块?Lodash Chunk不符合需求

我懂你想要的效果了——把对象数组分成2或3组,而且要把多出来的元素合理分配(比如100个元素分3组时,前两组各33个,最后一组34个),Lodash的chunk确实没法直接满足这种自定义的均衡分配逻辑对吧?下面给你几个实用的实现方案:

自定义分组实现方案

原生JavaScript函数实现

这个函数可以灵活处理分成2或3组的场景,自动把剩余元素分配到最后几个组中:

function splitArrayIntoGroups(arr, groupCount) {
  const result = [];
  const totalItems = arr.length;
  const baseGroupSize = Math.floor(totalItems / groupCount);
  const extraItems = totalItems % groupCount;

  let currentIndex = 0;
  for (let i = 0; i < groupCount; i++) {
    // 前 (groupCount - extraItems) 个组用基础大小,剩下的组多一个元素
    const currentGroupSize = i < groupCount - extraItems ? baseGroupSize : baseGroupSize + 1;
    result.push(arr.slice(currentIndex, currentIndex + currentGroupSize));
    currentIndex += currentGroupSize;
  }

  return result;
}

代码说明

  • 先计算每组的基础大小baseGroupSize,以及剩余无法均分的元素数量extraItems
  • 循环创建分组:前groupCount - extraItems个组使用基础大小,剩下的extraItems个组各多分配一个元素,这样就实现了剩余元素的合理分配
  • 如果想要把剩余元素分配到前几个组(比如100个元素分3组时得到34、33、33),只需要把判断条件改成i < extraItems ? baseGroupSize + 1 : baseGroupSize即可

测试示例

// 生成100个测试对象
const testArray = Array.from({ length: 100 }, (_, index) => ({ id: index + 1 }));

// 分成3组
const groupsOf3 = splitArrayIntoGroups(testArray, 3);
console.log(groupsOf3.map(group => group.length)); // 输出: [33, 33, 34]

// 分成2组
const groupsOf2 = splitArrayIntoGroups(testArray, 2);
console.log(groupsOf2.map(group => group.length)); // 输出: [50, 50]

// 测试101个元素分2组的情况
const testArray101 = Array.from({ length: 101 }, (_, index) => ({ id: index + 1 }));
const groupsOf2_101 = splitArrayIntoGroups(testArray101, 2);
console.log(groupsOf2_101.map(group => group.length)); // 输出: [50, 51]

这个方案完全不需要依赖第三方库,逻辑清晰,还能根据你的需求调整剩余元素的分配位置,比Lodash的chunk更贴合你的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:19:19