Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put items in an array sequentially?(javascript)

Tags:

javascript

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.

like image 649
nakzyu Avatar asked Mar 13 '20 13:03

nakzyu


3 Answers

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);
like image 140
huytc Avatar answered Oct 26 '22 20:10

huytc


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
});
like image 23
Taki Avatar answered Oct 26 '22 22:10

Taki


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;
}
like image 33
Nandu Kalidindi Avatar answered Oct 26 '22 20:10

Nandu Kalidindi