0 day streak
javascript / beginner
Snippet

Filtering Array Elements Dynamically Before Rendering in Svelte

Using JavaScript's built-in Array.prototype.filter method within a Svelte reactive declaration ($:) produces a derived subset of items whenever the base collection changes, without mutating the original source array.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
let items = [
{ id: 1, name: "Milk", completed: true },
{ id: 2, name: "Bread", completed: false },
{ id: 3, name: "Coffee", completed: false }
];
$: remainingItems = items.filter(item => !item.completed);
</script>
<h2>Open Tasks ({remainingItems.length})</h2>
<ul>
{#each remainingItems as item (item.id)}
<li>{item.name}</li>
{/each}
</ul>
svelte
Breakdown
1
let items = [
Defines an array of task objects with unique IDs and completion states.
2
$: remainingItems = items.filter(item => !item.completed);
Creates a reactive array containing only uncompleted items via the filter method.
3
{#each remainingItems as item (item.id)}
Iterates over the filtered array items, using item.id as a unique keyed identifier.