I wonder the title is right or not,
anyway what I wonder is how can do thing like this
const items = [a1,a2,a3,a4,a5,a6,a7,a8,a9 .. and so on ]
const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];
for (const item in items) {
// what I wonder is this part.
}
==> result:
const flexbox1 = [a1,a5,a9,a13 .. and so on];
const flexbox2 = [a2,a6,a10,a14 .. and so on];
const flexbox3 = [a3,a7,a11,a15 .. and so on];
const flexbox4 = [a4,a8,a12,a16 ... and so on];
How can I get the results above??
I've been trying for two days to find the answer in the book and on the internet, but I couldn't find it.
please help ....
Thanks in advance.
const items = [...Array(20).keys()];
const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];
const boxes = [flexbox1, flexbox2, flexbox3, flexbox4];
items.forEach((item, index) => {
boxes[index % 4].push(item);
});
console.log(flexbox1);
console.log(flexbox2);
console.log(flexbox3);
console.log(flexbox4);
use a simple for
loop incrementing the counter by 4 :
const items = Array.from({ length: 40 }, (_, i) => "a" + (i+1));
const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];
for (let i = 0; i < items.length; i += 4) {
flexbox1.push(items[i]);
flexbox2.push(items[i + 1]);
flexbox3.push(items[i + 2]);
flexbox4.push(items[i + 3]);
}
console.log({
flexbox1,
flexbox2,
flexbox3,
flexbox4
});
Below is one approach to put items into the 4 buckets using the modulo operator. This solution can be extended to account for any number of buckets. The function allocateFlexboxes
in the snippet achieves just that.
Once the for
loop ends, you can access desired flexbox by the index.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let flexBoxes = [[], [], [], []];
for (let i=0; i<items.length; i++) {
const bucketIndex = i % 4;
flexBoxes[bucketIndex].push(items[i]);
}
console.log("Bucket size: 4");
console.log(flexBoxes);
// Generic function that can accommodate for any number
const allocateFlexboxes = (items, flexBoxCount) => {
let flexBoxes = [...new Array(flexBoxCount)].map(x => [])
items.forEach((item, index) => {
const bucketIndex = index % flexBoxCount;
flexBoxes[bucketIndex].push(item);
});
return flexBoxes;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With