I've found a lot of answers to the question "how to split an array in multiple chunks", but I can't find a way to best repartition the array. For example,
let x = [1,2,3,4,5,6,7,8,9,10,11,12,13];
//#Source https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-265.php
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
const n = 10;
console.log(chunk(x,n))
Run Code Online (Sandbox Code Playgroud)
This function gives me two arrays: [1,2,3,4,5,6,7,8,9,10] and [11,12,13]. But I would prefere n to be used as a "max" to obtain [1,2,3,4,5,6,7] and [8,9,10,11,12,13]. This way I would have two arrays of the same size. If it is possible for the selected n, they should be of equal size, otherwise, two arrays with a nearly identical size.
我将其分为 3 个步骤。
numChunks,你需要多少块?例如,如果您有一个包含 103 个元素的数组,最大大小为 10,那么您将需要 11 个块。minChunkSize较小块的大小。例如,在上面的示例中,前 7 个块将有 10 个元素,而其他 3 个块将有 11 个元素 (7 10 + 3 11 = 103)。numSmallChunks你可以有多少个小块。例如上面例子中的3。然后你只需相应地拼接即可arr。
let chunk = (arr, maxSize) => {
let numChunks = parseInt((arr.length - 1) / maxSize) + 1;
let minChunkSize = parseInt(arr.length / numChunks);
let numSmallChunks = numChunks * (minChunkSize + 1) - arr.length;
arr = [...arr]; // avoid muckking the input
let arrays = [];
for (let i = 0; i < numChunks; i++)
if (i < numSmallChunks)
arrays.push(arr.splice(0, minChunkSize));
else
arrays.push(arr.splice(0, minChunkSize + 1));
return arrays;
};
let x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
for (let i = 1; i < x.length; i++)
console.log(i, JSON.stringify(chunk(x, i), null, ''));Run Code Online (Sandbox Code Playgroud)
注意,其他答案会导致不平衡;例如,当 为 4 时,它们会生成大小为 4、4、4 和 1 的数组。n而我的方法会生成大小为 3、3、3 和 4 的数组。我想这取决于您需要的情况,但这就是我的方式解释问题的“平等块”。