I\'m using this function to create chunks of an array:
function chunkArray(myArray, chunk_size) {
let results = [];
while (myArray.length) {
You can use the following code:
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)
You could use the remainder of the index with the wanted size for the index and push the value.
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; }
I'd do something like this:
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;
}