Search code examples
javascripthtmlarrayssvelteeach

Is it possible to limit results from Svelte {#each} loop by a certain amount?


I'm using an {#each} loop to showcase data, but I'm curious if Svelte has a way to limit the results by an integer.

For example, if I had the following array and loop:

const object = [1, 2, 3, 4, 5];

{#each objects as object, i}
<div>{object}</div
{/each}

// result:

<div>1<div>
<div>2<div>
<div>3<div>
<div>4<div>
<div>5<div>

Is there anything along the lines of:

{#each objects as object, i, limit 3}
<div>{object}</div
{/each}

// result:

<div>1<div>
<div>2<div>
<div>3<div>

Solution

  • Just slice the array.

    {#each objects.slice(0, 3) as object, i}
    

    (Can also be extracted to the <script> via a $: statement/$derived in Svelte 5.)