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;
}
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]
]
What would be the best way to do this?
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;
}