Search code examples
javascriptarraysmodulus

JavaScript - Wrap every 3 items from an array to a div


I have an array consists 50 items.

I want to wrap every 3 items to a <div>.

I'm cracking my head trying to achieve this but I can't get it to work


var cards = [];

for(var i=0; i < 50; i++){
    cards.push('<div class="card-item">Test</div>');
}

for(var i = 0; i < cards.length; i++){
    if(i % 3 === 0){
        let slides = populateSlide(cards[i]);
        console.log(slides);
    }
}

populateSlide = (cards) => {
    return `<div class="carousel-item item">${cards}</div>`;
}

Using the code above, I only managed to get a single item in every multiply of 3. Hence my div only has single item instead of three.

Thanks in advance.


Solution

  • You can store the cards in a temporary array and check its length. Something like:

    {
      const populateSlide = cards => {
          console.log(cards)
      }
      const cards = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      let cardsTriple = []; // the temporary array
    
      cards.forEach( card => {
          cardsTriple.push(card); // add card to temp array
          if(cardsTriple.length === 3){
              let slides = populateSlide(cardsTriple);
              cardsTriple = []; // reset the temp array
          }
      });
    
      // there may still be cards available
      if (cardsTriple.length) {
        populateSlide(cardsTriple);
      }
    }
    .as-console-wrapper { top: 0; max-height: 100% !important; }