Reputation: 21751
<script>
let cats = [
{ 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 cats as cat, i}
{#if i % 4 === 0}
<div class="row">
<div class="card-group">
<div class="card">{cats[i].name}</div>
<div class="card">{cats[i + 1].name}</div>
<div class="card">{cats[i + 2].name}</div>
<div class="card">{cats[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
Upvotes: 0
Views: 74
Reputation: 1821
I would create another array out of cats
array. the new array will include sub-arrays each array will include at most 4 elements.
then in the HTML, we iterate over the new array then iterate over the sub arrays
/* divide your elements into another array where each index is a sub array array of 4 elements */
let chunkit = (maxItems = 4) => {
/* array to store the sub arrays of 4 elements */
let chunks = [[]]
/* iterate over the cats */
for (let cat of cats) {
/* if the last array of 4 elements has the length of 4, we create a new sub-array */
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
}
then we iterate over the return value of the function chunkit
<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 pass a number as parameter to the function maxItems
to set the number of elements in each sub category
here is an example repl
Upvotes: 1