// 示例数组
const dataArray = Array.from({ length: 21 }, (_, index) => index + 1);
// 调用函数以分配数据到小于或等于3组的数组,每组基础数据需大于等于5,且每组都必须是5的倍数,除了最后一页
const groupedArrays = splitArrayIntoGroups(dataArray, 3, 5);
// 输出分出来的数组组
groupedArrays.forEach((group, index) => {
console.log(`Group ${index + 1}:`, group);
});
/*输出结果为:3组,每组内为5的倍数的数量
Group 1: (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Group 2: (10) [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Group 3: [21]
*/
function splitArrayIntoGroups(array, maxGroupCount, minGroupSize) {//传入数组,二维数组最大数组个数,每组组内最小元素数量
const totalItems = array.length;
const groups = []; // 存储分组结果的数组
let currentIndex = 0; // 当前处理的数组索引
let groupSize = Math.ceil(totalItems / maxGroupCount); // 每组至少应有的元素数
// 确保组大小至少为5的倍数
groupSize = Math.max(groupSize, minGroupSize);//组内元素数和最小组内倍数比较大小,获取最大的一个
groupSize = Math.ceil(groupSize / minGroupSize) * minGroupSize; // 确保是5的倍数 (通过上面的比较获得的最大元素数/最小组内倍数并向上舍入为最接近的整数再乘以最小组内倍数,获得最后的每组元素数量)
// 循环分配数组对象到各个组
for (let i = 0; i < maxGroupCount && currentIndex < totalItems; i++) {
// 计算当前组的结束索引
const endIndex = Math.min(currentIndex + groupSize, totalItems);//获取对应每组元素数量的结束索引
// 提取当前组的数组对象
const group = array.slice(currentIndex, endIndex);
groups.push(group);
// 更新当前索引为下一组的开始位置
currentIndex = endIndex;
}
// 如果还有剩余的对象,将它们放入最后一组
if (currentIndex < totalItems) {
groups.push(array.slice(currentIndex));
}
return groups;
}
记录:js将一维数组转成二维数组,并且自定义二维数组内最大数组个数和每组数组内最小数量的函数
于 2024-04-08 09:38:21 首次发布