'Svelte - non-trivial intermediate variable within each loop

How can I create variables inside Svelte's HTML like in React, or is it not at all how I am supposed to use Svelte. I know the example below is trivial but I'm thinking of a case where I really need some heavy logic for subArray (could not use a one liner)

React

<ul>
  {myArray.map((item) => {
    const subArray = item.items.filter(i = i > 0) // <- how can I have an intermediate variable like this in Svelte?
    return <li>{subArray.map(...)}</li>
  }}
</ul>

Svelte

<ul>
  {#each myArray as item}
    <li>
        {#each <complex-logic> as subItem}
        ...
        {/each}
    </li>
  {/each}
</ul>


Solution 1:[1]

You can use the {@const} directive, which is a recent addition to Svelte. In your use case:

<ul>
  {#each myArray as item}
    {@const subArray = item.items.filter(i => i > 0)}
    <li>
        {#each subArray as subItem}
        ...
        {/each}
    </li>
  {/each}
</ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1