Show four rows of each item, with any remaining item displayed on a separate row

<script>
    let pets = [
        { id: 'OUtn3pvWmp1', name: 'Cat1' },
        { id: 'OUtn3pvWmp2', name: 'Cat2' },
        { id: 'OUtn3pvWmp3', name: 'Cat3' },
        { id: 'OUtn3pvWmp4', name: 'Cat4' },
        { id: 'OUtn3pvWmp5', name: 'Cat4' },
        { id: 'OUtn3pvWmp6', name: 'Cat6' },
        { id: 'OUtn3pvWmp7', name: 'Cat7' },
        { id: 'OUtn3pvWmp8', name: 'Cat8' },
        { id: 'OUtn3pvWmp9', name: 'Cat9' },
        { id: 'OUtn3pvWmp10', name: 'Cat10' },
        { id: 'OUtn3pvWmp11', name: 'Cat11' },
        { id: 'OUtn3pvWmp12', name: 'Cat12' },
        
        //{ id: 'OUtn3pvWmp13', name: 'Cat13' },
    ];
</script>
<style>
.row {
display: grid;
grid-columns: 4;
}
 .card{
    background-color: gray !important;
    color: white;
    border-radius: 10px;
    border-color: #404040;
      padding-left: 15px;
    padding-right: 15px;
  }
 
.card-group {
display: flex;
}
</style>

<h1>EXPECTED OUTPUT, BY LOOP OVER cats </h1>
{#each pets as pet, i}     
{#if i % 4 === 0}                   
<div class="row">         
    <div class="card-group">         
    <div class="card">{pets[i].name}</div>        
    <div class="card">{pets[i + 1].name}</div>      
    <div class="card">{pets[i + 2].name}</div>        
    <div class="card">{pets[i + 3].name}</div>                  
    </div>   
</div>                      
{/if} 
{/each}

I would like cat13 item display in the another row ,anyone please give some trick. I am using sveltejs 3

My runnable script here

Answer №1

To organize the elements in the cats array, I would create a new array containing sub-arrays with a maximum of four elements each.

In the HTML code, we would iterate through the new array and then iterate through the sub-arrays.

/* Split the elements into sub-arrays with a maximum of 4 elements each */
    let chunkit = (maxItems = 4) => {
        /* Array to hold the sub-arrays with 4 elements each */
        let chunks = [[]]
        /* Iterate through the cats array */
        for (let cat of cats) {
            /* If the last sub-array is full, create a new one */
            if (chunks[chunks.length - 1].length == maxItems) {
                chunks.push([])
            }
            /* Add the current element to the last sub-array */
            chunks[chunks.length - 1].push(cat)
        }
        return chunks
    }

We then loop through the output of the chunkit function.

<div class="row">
    {#each chunkit() as fourCats}
        <div class="card-group">
            {#each fourCats as cat}
                <div class="card">{cat.name}</div>        
            {/each}
        </div>  
    {/each}
</div>

You can specify the number of elements in each sub-category by passing a parameter to the maxItems function.

Here's an example on repl

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

What is the proper method for initiating an ajax request from an EmberJs component?

Curious to learn the correct method of performing an ajax call from an Ember component. Let's say, for instance: I am looking to develop a reusable component that allows for employee search based on their Id. Once the server responds, I aim to update ...

Manipulating the DOM results in the SWF being reloaded

Currently, I am utilizing jQuery to insert an SWF into the DOM. However, when the SWF loads and I attempt to clone or wrap it, the SWF ends up reloading. Preventing this reload is crucial for me. Here's an example: $('#test9').before(&apo ...

How can I create a jumping animation effect for my <li> element in JQuery?

I have a horizontal navigation bar with a "JOIN" option. My goal is to make the #jump item continuously jump up and down after the page has finished loading. Currently, I have this code which only triggers the jump effect once when hovering over the eleme ...

Angular Datepicker MinDate function prevents selection of dates "behind" by one

I've encountered an issue with the Angular Bootstrap Datepicker where I'm setting the min-date attribute as follows: <input type="text" class="" uib-datepicker-popup="MM/dd/yyyy" show-button-bar="false" ng-model="vm.date" ng-change= ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

`Active the button once user checks one or more checkboxes using AngularJS`

I'm working on a project where I have checkboxes and a button. I need to figure out how to activate the button when one or more checkboxes are checked using AngularJS. Can anyone provide some guidance? <script src="https://ajax.googleapis.com/aj ...

Assign individual heights to multiple iFrames according to their content's height

Dealing with multiple iframes on a single page. Each iframe is sourced from my domain. The goal is to automatically calculate and set the height of each iframe on the page. The current code sets all iframe heights to match that of a specific iframe: fun ...

Can't I prevent additional renders using useMemo()?

I am facing an issue with my function-based component that fetches data using redux toolkit and useAppSelector(). I have placed a console.log within the component to monitor its behavior. However, upon refreshing the page, the console.log continues to appe ...

Unlocking the Power of Localization: An Easy Guide to Accessing JavaScript Values

After utilizing the localization helper created by Matt Hawley, I found it to be incredibly effective. However, I am encountering an issue when attempting to retrieve the values in javascript/jQuery. For example, I am unable to fetch the resource text usi ...

Undo the creation of a record in Ember data when there is an error

I'm currently exploring the most effective method to prevent adding a record when encountering an error using Ember Data: Here's the code snippet in question: createUser: function() { // Create the new User model var user = this.store.creat ...

Tips on creating the <th> tag just one time

I have a task that involves dynamically creating cells in a table based on an array of data. However, I am unsure how to also create a header cell for this table within the same function. Is there a way to streamline the process and create the entire table ...

Error: The property 'parentNode' cannot be read because it is null

I wanted to test if my laptop can handle WebGL by loading examples from my instructor's webpage. The examples on the webpage worked fine, just showing a square within a square. I then decided to copy the exact codes into a notepad text editor, saved t ...

What is the best way to incorporate arrow buttons on my website in order to unveil various sections on the homepage?

A colleague and I are collaborating on a website for his cookery business. He has sketched out some design ideas on paper, one of which involves having a homepage with 4 different sections stacked on top of each other. Each section would have an arrow butt ...

What could be causing my checkbox to become unresponsive and fail to reset?

I recently created a function to update my page title when the toggle button is clicked, but unfortunately, it seems to be getting stuck after the click. I can't seem to pinpoint the issue with this function, as I've tried coding it in both JQuer ...

Is it possible to send a Word file as an email attachment using PHP's mail() function

When I sent a Word document file via email, it generated an unknown format like asdfADFDF 0000sadfas15454454. The mail function was used to send the email. Below is the code for that. Please review and let me know: function sendfile() { $id = $_REQU ...

Layered parallax scenery

I'm interested in creating a parallax effect similar to this example. https://medium.com/@PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27 However, I find the use of HAML and Coffeescript in the mentio ...

Access parent component's properties by clicking on child component

I'm uncertain if my current approach is the most effective solution to my issue, so I am open to alternative methods. My goal is to access the properties of the parent component when clicking on a child component (Image). Below is the code I have imp ...

AngularJS throwing error due to additional content following the document element during XML parsing

I've been working with Angular JS and recently created a basic login form with routing to navigate to the next page upon successful login. However, I've encountered an issue when trying to implement conditional routing. Although I can successful ...