Svelte List Patterns

Real apps rarely show a list exactly as it arrives. Visitors search, sort, and page through items. Combining reactive statements with each blocks handles all of these jobs with short, readable code.

Search And Sort Together

The example below filters a book list by a typed word and sorts the result by page count. Two reactive declarations chain together, and each stage feeds the next.

<script>
  let search = "";
  let ascending = true;

  let books = [
    { id: 1, title: "Cloud Basics", pages: 220 },
    { id: 2, title: "Web Design", pages: 180 },
    { id: 3, title: "Data Skills", pages: 310 }
  ];

  $: filtered = books.filter((book) =>
    book.title.toLowerCase().includes(search.toLowerCase())
  );

  $: sorted = [...filtered].sort((a, b) =>
    ascending ? a.pages - b.pages : b.pages - a.pages
  );
</script>

<input bind:value={search} placeholder="Search title" />
<button on:click={() => (ascending = !ascending)}>Flip Order</button>

{#each sorted as book (book.id)}
  <p>{book.title} ({book.pages} pages)</p>
{:else}
  <p>No books match your search.</p>
{/each}

The sort step copies the array with the spread syntax before sorting. The sort method rearranges an array in place, and a copy protects the original list from surprise changes.

List Pipeline Diagram

books (original list)
      |
      v
Filter by search text
      |
      v
Sort by page count
      |
      v
Slice for the current page
      |
      v
{#each} draws the rows on screen

Empty States

The else clause inside an each block runs when the list has no items. Friendly messages guide visitors better than a blank area. A good empty state tells people what happened and what to try.

Pagination

Large lists feel heavy when shown all at once. A slice shows only a window of items. Two variables control the window: the page number and the page size.

<script>
  export let rows = [];
  let page = 0;
  const pageSize = 5;

  $: totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  $: visible = rows.slice(page * pageSize, (page + 1) * pageSize);
</script>

{#each visible as row (row.id)}
  <p>{row.title}</p>
{/each}

<button disabled={page === 0} on:click={() => page--}>Back</button>
<span>Page {page + 1} of {totalPages}</span>
<button disabled={page + 1 >= totalPages} on:click={() => page++}>Forward</button>

A search box changes the list length, so the page number can point past the end. Reset page to zero whenever the search text changes.

Nested Lists

An each block can sit inside another each block. Categories holding products show this pattern clearly.

{#each categories as category (category.id)}
  <h4>{category.name}</h4>
  {#each category.items as item (item.id)}
    <p>{item.label}</p>
  {/each}
{/each}

Showing A Counter

The length of the filtered list gives an instant result count. Display it near the search box so visitors see the effect of each keystroke.

<p>{sorted.length} of {books.length} books shown</p>

A Layman Analogy

Think of a library shelf. A visitor asks the librarian for books on one subject, and the librarian pulls matching titles. The librarian arranges them by thickness and carries only one armful to the reading table. Filtering, sorting, and slicing follow the same three actions.

Common Mistakes To Avoid

  • Sorting the original array directly and changing data other parts of the page use
  • Forgetting a unique key in each blocks that reorder items
  • Leaving the page number unchanged after a search shrinks the list
  • Skipping the empty state message

Key Points

  • Chain reactive declarations to build filter and sort stages
  • Copy arrays before sorting
  • Use the else clause for empty lists
  • Slice arrays to build pagination