Alex
Alex

Reputation: 391

Break iteration (each) in Svelte?

Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")? For example:

{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}

Upvotes: 8

Views: 9084

Answers (3)

supafiya
supafiya

Reputation: 137

I just use a {#each myItems as item}{#if yourtruevalue} {item} {/if} {/each} I don't know about the performance impact but it's very simple. if yourtruevalue is true - whatever the condition is for the item to render - it will render, and skip the item if not.

Upvotes: 1

user2803857
user2803857

Reputation:

Svelte currently has no special syntax for breaks or ranges. (here's a pending proposal) A common idiom is to use a {length: N} object as the #each parameter, which usually performs better than creating new arrays every render.

{#each {length: 4} as _, i} {items[i]} {/each}

Here are some other patterns that work:

<script>
    let items = ['a', 'b', 'c', 'd', 'e'];
    $: filteredItems = items.slice(0, 4);
    const filterItems = (i) => i.slice(0, 4);
</script>

<div>
    {#each {length: 4} as _, i}
        {items[i]}
    {/each}
</div>
<div>
    {#each items.slice(0, 4) as item}
        {item}
    {/each}
</div>
<div>
    {#each filteredItems as item}
        {item}
    {/each}
</div>
<div>
    {#each filterItems(items) as item}
        {item}
    {/each}
</div>

Upvotes: 19

Tholle
Tholle

Reputation: 112787

There is no {:break} block, but you could slice out the first 4 elements in the array before you iterate over it.

{#each items.slice(0, 4) as item, i} ... {/each}

Upvotes: 15

Related Questions