javascript / beginner
Snippet
Filtering Active Todos with Array Filter in Vue
The Array.prototype.filter() method creates a shallow copy of an array containing only the elements that pass the test implemented by the provided function. In Vue, pairing filter() with a computed property ensures the active list recalculates reactively whenever the original array changes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ref, computed } from 'vue';export default {setup() {const todos = ref([{ id: 1, text: 'Buy groceries', done: false },{ id: 2, text: 'Clean kitchen', done: true },{ id: 3, text: 'Read book', done: false }]);const activeTodos = computed(() => {return todos.value.filter(todo => !todo.done);});return { todos, activeTodos };}};
vue
Breakdown
1
const todos = ref([ ... ]);
Defines a reactive array of todo objects containing completed status flags.
2
return todos.value.filter(todo => !todo.done);
Iterates through the list and returns a new array with items where 'done' is false.