Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly.

<% include ../partials/header %>
<div class="jumbotron jumbotron-fluid">
  <div class="container">
    <h1 class="display-4">Meet our Board of Directors!</h1>
  </div>
</div>
<% let cards = 5;
let totalCard = 0;
for(i = 0; i < cards; i++) {
if (i % 3 === 0) { %>
  <div class="card-group text-center">

  <% for(let numCards = 0;  numCards < 3 || totalCard === cards; numCards++) { %>
    <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <% totalCard++} %>

  </div>
<% numCards = 0; } } %>


<% include ../partials/footer %>

So far, the initial loop is running smoothly!

for(i = 0; i < cards; i++) {
if (i % 3 === 0) { %>
  <div class="card-group text-center">
<% } } %>

The issue lies within the nested loop

<% for(let numCards = 0;  numCards < 3 || totalCard === cards; numCards++) { %>
<div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
</div>
<% totalCard++} %>

The goal is to generate at least three cards inside each

<div class="card-group text-center">

For reference, you can view the expected outcome here

Desired hard-coded output is as follows:

<!-- First Div Generated -->
<div class="card-group text-center">
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
</div>

<!-- Second Div Generated -->
<div class="card-group text-center">
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
</div>
</div>

Answer №1

 <% let apples = 10, perBasket = 6; %>
 <% for(let basket = 0; basket < apples/perBasket + 1; basket++){ %>
    <div id= "basket">
      <% for(let j = 0; j < 3 && j + basket * perBasket < apples; j++){ %>
        <div id = "fruit" ></div>
     <% } %>   
    </div>      
 <% } %>

Answer №2

If you have a large array, it's best to chunk it out before processing. You can then use a nested loop to display each group on the page. First, loop through the card groups to create rows, and then within each iteration, loop through the cards in that group.

var cards = ["one", "two", "three", "four", "five"]

var cardgroups = []

while(cards.length > 0){
  let chunksize = cards.length < 3 ? cards.length : 3 //if more than 3 exist, grab the next group of 3
  
  cardgroups.push(cards.splice(0, chunksize)) //add the next chunk to the array
}

console.log(cardgroups)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterating through an instance of stdClass named "object1"

object(stdClass)#1 (1) { ["trackingNo"]=> array(18) { [0]=> string(15) " 888005324912 " [1]=> string(16) " 1900530244582 " [2]=> string(15) " 778180519352 " [3]=> string(16) " 1000237325384 " Is there ...

Ideas for effectively reusing MongoDB Mongoose queries in Node.js

Can you re-use an existing exec mongodb/mongoose query in nodejs? For example, let's say I create a query like this to check if a user exists: const inviter = await User.findOne({ _id: req.userData._id }).exec() // There is more code below before upd ...

Managing the parallel processing of messages with ConsumerGroup

Currently, I am utilizing the kafka-node ConsumerGroup to retrieve messages from a specific topic. However, upon consuming a message, a call to an external API is necessary, and it can potentially take up to a second for a response to be received. My goal ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

Instead of JSON data, HTML is being transmitted

I'm facing an issue where I am attempting to retrieve data from a SQL database and showcase it on a Reactjs web app. However, each time I make a call to the database, the HTML content of the current webpage is displayed instead. I have ensured that th ...

Having trouble with the tooltip feature in Bootstrap?

I've searched high and low, including on this site! I've experimented with all sorts of code, but nothing seems to make the tooltips function in BootStrap. It's beginning to really frustrate me!! Does anyone happen to have the working js co ...

The response in node.js is formatted as junk data

I am currently working on developing an API using Node.js. One issue I have encountered is that when I access a specific URL through my browser, I receive a perfectly formatted JSON response. However, when I try to retrieve the same response in my Node.js ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Webpack2 now transforms sass/scss files into JavaScript rather than CSS during compilation

I've created a webpack script to compile all .scss files into one css file. I decided to use webpack instead of gulp or grunt for simplicity, as it can be configured in a single file. However, I am encountering an issue where scss files are being com ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Differences in mounted volumes between using "up" and "run" in docker-compose

Update Alert 2: I've developed a demo project on GitHub to replicate this issue. After further testing, the scenario is slightly different from what I initially explained. Below you'll find the details of the README I created on the GitHub repos ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...

Preventing preventDefault() from firing in JQuery only when necessary

I have come up with a script that I recently created. <script> $(document).ready(function(){ $('a').data('loop',true); $('body').on('click', 'a', function(event){ console.lo ...