5

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.

9 Answers 9

11

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);

Sign up to request clarification or add additional context in comments.

Comments

6

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
});

3 Comments

Of all answers this is most efficient in terms of performance.
this might push undefined onto flexbox2, flexbox3 and flexbox4 in case of array length being not divisible by 4
you might consider changing the condition of the for loop to i<items.length -3 and manually pushing the last few elements outside of the loop if they exist
6

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;
}

1 Comment

I was too slow in writing my solution, so no need to post a further answer. +1 to this one because it is clean (and it has at least a minimal explanation)
4

const items = ['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12']

const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];



items.forEach((item,index)=> {
  if( index%4 ==0 ) { flexbox1.push(item) }
  else if( index%4 ==1 ) { flexbox2.push(item) }
  else if( index%4 ==2 ) { flexbox3.push(item) }
  else if( index%4 ==3 ) { flexbox4.push(item) }
})


console.log(flexbox1);
console.log(flexbox2);
console.log(flexbox3);
console.log(flexbox4);

Comments

4

I think it is not the cleanest solution, but it should work :)

const items = [...Array(20).keys()];

let currentIndex = 1;
const data = {
  flexbox1: [],
  flexbox2: [],
  flexbox3: [],
  flexbox4: []
};

for (const item in items) {
  data[`flexbox${currentIndex}`].push(item);
  currentIndex = currentIndex === 4 ? 1 : currentIndex + 1;
}

console.log(data);

Comments

3

let r1 = [], r2 = [], r3 = [], r4 = [];
let x = 0;
const items = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"];
for (let i = 0; i < items.length - 1; i++) {
if (x % 4 === 0) {
    r1.push(items[i]);
    x++;
} else if (x % 4 === 1) {
    r2.push(items[i]);
    x++;
} else if (x % 4 === 2) {
    r3.push(items[i]);
    x++;
} else if (x % 4 === 3) {
    r4.push(items[i]);
    x++;
}
}
console.log(r1, r2, r3, r4);

Comments

3

Since you want to allocate items in 4 different arrays, you can push each item to a different array according to their index modulo 4.

const items = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10']

const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];

const flexboxes = [flexbox1, flexbox2, flexbox3, flexbox4];

items.map((item, index) => {
  flexboxes[index%4].push(item);
});

Comments

2

I had to do this once upon a time. Here's the function I wound up writing. It takes a slightly different approach than pushing items into an array. I have no idea if it's faster, but all the array sizes are known up front with this approach. It also handles having leftover columns and having too few items to fill all rows.

let to2D = (items, n) => [...Array(Math.min(items.length, n))].map(
  (_, row) => [...Array((items.length + n - 1 - row) / n >>> 0)].map(
    (_, column) => items[column * n + row]
  )
);


let exampleItems = [...Array(17).keys()].map(i => `a${i + 1}`);
console.log(to2D(exampleItems, 4))

FYI Output:

[
  [ 'a1', 'a5', 'a9', 'a13', 'a17' ],
  [ 'a2', 'a6', 'a10', 'a14' ],
  [ 'a3', 'a7', 'a11', 'a15' ],
  [ 'a4', 'a8', 'a12', 'a16' ]
]

Comments

1

An approach could be something like this:

for (var i = 0; i < items.length; i++) {
  flexbox1.push(items[4 * i]);
  flexbox2.push(items[4 * i + 1]);
  flexbox3.push(items[4 * i + 2]);
  flexbox4.push(items[4 * i + 3]);

}

const items = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"]

const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];


for (var i = 0; i < items.length; i++) {
  flexbox1.push(items[4 * i]);
  flexbox2.push(items[4 * i + 1]);
  flexbox3.push(items[4 * i + 2]);
  flexbox4.push(items[4 * i + 3]);

}

document.querySelector('.foo').innerHTML = flexbox1 + "<br>" + flexbox2 + "<br>" + flexbox3 + "<br>" + flexbox4;
<div class="foo"></div>

This method isn't perfect as it keeps adding elements in the array until the items.length is reached, but should be enough to get the idea.

1 Comment

There was no need to add extra jsFiddle demo, as you already added a working code snippet demo here. Just wanted to let you know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.