本文探讨如何将javascript数组平均分组,并提供两种分组格式的实现方案。 问题在于将一个长度未知的数组(例如,14个元素)平均分成指定数量的组(例如,5组),且尽可能保证每组元素数量均衡。
目标输出格式有两种:
格式一:索引间隔相同
{ '0': [1, 6, 11], '1': [2, 7, 12], '2': [3, 8, 13], '3': [4, 9, 14], '4': [5, 10] }
格式二:连续索引
{ '0': [1, 2, 3], '1': [4, 5, 6], '2': [7, 8, 9], '3': [10, 11, 12], '4': [13, 14] }
改进后的代码实现:
立即学习“Java免费学习笔记(深入)”;
以下代码分别实现了两种格式的分组,并解决了原代码中组数不固定的问题,能够精确地按照指定组数进行分组:
格式一:索引间隔相同
function groupArrayByInterval(arr, numGroups) { const result = {}; const groupSize = Math.floor(arr.length / numGroups); const remainder = arr.length % numGroups; let index = 0; for (let i = 0; i < numGroups; i++) { const group = []; const currentGroupSize = groupSize + (i < remainder ? 1 : 0); // 处理余数 for (let j = 0; j < currentGroupSize; j++) { group.push(arr[index]); index += numGroups; // 索引间隔为组数 } result[i] = group; } return result; } let arr = Array.from({length: 14}, (_, i) => i + 1); // 创建一个长度为14的数组 let groupedArray = groupArrayByInterval(arr, 5); console.log(groupedArray);
格式二:连续索引
function groupArrayConsecutive(arr, numGroups) { const result = {}; const groupSize = Math.floor(arr.length / numGroups); const remainder = arr.length % numGroups; let startIndex = 0; for (let i = 0; i < numGroups; i++) { const groupSize = Math.floor(arr.length / numGroups) + (i < remainder ? 1 : 0); result[i] = arr.slice(startIndex, startIndex + groupSize); startIndex += groupSize; } return result; } let arr2 = Array.from({length: 14}, (_, i) => i + 1); // 创建一个长度为14的数组 let groupedArray2 = groupArrayConsecutive(arr2, 5); console.log(groupedArray2);
这两个函数都接受数组 arr 和组数 numGroups 作为参数,并返回一个对象,其中键为组索引,值为该组的数组元素。 它们有效地处理了余数,保证所有元素都被分配到组中,并且准确地按照指定的组数进行分组。 代码更清晰,可读性更强,并且直接解决了原代码中组数不确定的问题。
以上就是JavaScript数组如何平均分组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号