Skip to content

How to iterate over a linked list in Svelte? (Or how to use a while loop / recursion?) #13159

Answered by brunnerh
Saad5400 asked this question in Q&A
Discussion options

You must be logged in to vote

You can wrap the iteration logic in a generator function and use that in #each.

E.g. if the items have the shape { value, next } and end with next being null:

function* iterate(list) {
    let current = list;
    while (current != null) {
        yield current.value;
        current = current.next;
    }
}
{#each iterate(list) as item}
    <div>{item}</div>
{/each}

REPL

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Saad5400
Comment options

Answer selected by Saad5400
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants