我如何将数组拆分成块,但让它逐个填充每个数组 [英] How can I split an array into chunks but have it fill each array by going one by one
本文介绍了我如何将数组拆分成块,但让它逐个填充每个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此函数创建数组的块:
I'm using this function to create chunks of an array:
function chunkArray(myArray, chunk_size) {
let results = [];
while (myArray.length) {
results.push(myArray.splice(0, chunk_size));
}
return results;
}
但是,如果我们假设原始数组是 [1,2,3,4,5,6]
我将它分成3个部分,我最终会得到这个:
However, if we assume that the original array is [1, 2, 3, 4, 5, 6]
and I'm chunking it into 3 parts, I'll end up with this:
[
[1, 2],
[3, 4],
[5, 6]
]
但是,我更愿意将它分成三个之间的数组,例如:
But, I'd instead like it to chunk into the arrays jumping between the three, ex:
[
[1, 4],
[2, 5],
[3, 6]
]
最好的方法是什么?
推荐答案
您可以使用以下代码:
function chunkArray(myArray, chunk_size) {
let results = new Array(chunk_size);
for(let i = 0; i < chunk_size; i++) {
results[i] = []
}
// append arrays rounding-robin into results arrays.
myArray.forEach( (element, index) => { results[index % chunk_size].push(element) });
return results;
}
const array = [1,2,3,4,5,6];
const result = chunkArray(array, 3)
console.log(result)
这篇关于我如何将数组拆分成块,但让它逐个填充每个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文