我正在使用此函数来创建数组的块:
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部分,那么我将得出以下结论:
[
[1, 2],
[3, 4],
[5, 6]
]
但是,我希望将其分块到三个之间的数组中,例如:
[
[1, 4],
[2, 5],
[3, 6]
]
什么是最好的方法?
答案 0 :(得分:2)
您可以使用以下代码:
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)
答案 1 :(得分:2)
您可以使用索引的其余部分以及所需的索引大小,然后推入该值。
var array = [1, 2, 3, 4, 5, 6],
size = 3,
result = array.reduce((r, v, i) => {
var j = i % size;
r[j] = r[j] || [];
r[j].push(v);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
我会做这样的事情:
function chunkArray(src, chunkSize ) {
const chunks = Math.ceil( src.length / chunkSize );
const chunked = [];
for (let i = 0; i < src.length; ++i) {
const c = i % chunks;
const x = chunked[c] || (chunked[c]=[]);
x[ x.length ] = src[i];
}
return chunked;
}