Let's say I have an array and I want to iterate over them N at a time. I can use a simple nested loop
const array = ['a','b','c','d','e','f','g','h'];
const step = 3;
for (let i = 0; i < array.length; i += step) {
const end = Math.min(i + step, array.length);
console.log("page:", i / step);
for (let j = i; j < end; ++j) {
const element = array[j];
console.log(" ", element);
}
}
outputs:
page: 0
a
b
c
page: 1
d
e
f
page: 2
g
h
But I'm wondering if there's a more modern way, forEach like way in JavaScript now-a-days. Imagine:
// pseudo code
const chunkSize = 3
forEachByChunk(array, chunkSize, (subArray, chunkNdx, startingNdxInParentArray) => {
console.log("page:", chunkNdx);
subArray.forEach((element) => { console.log(" ", element); });
});
Note: I can write my own forEachByChunk
function forEachByChunk(array, chunkSize, fn) {
const end = array.length;
for (let i = 0; i < end; i += chunkSize) {
fn(array.slice(i, i + chunkSize), i / chunkSize, i);
}
}
I'm just wondering if there isn't already some built in modern way to do this in JavaScript. Or maybe a more generic version.