Array Functions - filter
Hey there, coder! 👋
In this tutorial, we're going to explore the filter method of arrays in JavaScript. We'll use a real-world example to extract only the completed tasks from a to-do list.
Your Task
Open the index.js file and get ready to code! 💻
The Problem
Imagine you have a to-do list with several tasks, and you want to extract only the tasks that are completed. Here's an example of the data:
const tasks = [ { id: 1, task: "Buy milk", completed: true }, { id: 2, task: "Walk the dog", completed: false }, { id: 3, task: "Do laundry", completed: true }, { id: 4, task: "Study for exam", completed: false },]
Your task is to write a function that takes this array of tasks as an input and returns a new array with only the completed tasks.
Using filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function. In our case, we'll use it to filter out the completed tasks.
Add the following code to your index.js file:
const completedTasks = tasks.filter((task) => task.completed)
Here, we're using an arrow function as the callback function for filter(). The function takes each task object as an argument and returns true if the task is completed (completed property is true) and false otherwise.
Run the Code
Click the "Run" button to execute the code. You should see the output in the console.
What to Expect
The output should be an array with only the completed tasks:
[ { id: 1, task: 'Buy milk', completed: true }, { id: 3, task: 'Do laundry', completed: true },]
How it Works
The filter() method iterates over the tasks array and applies the callback function to each element. If the callback function returns true, the element is included in the new array. In our case, we're filtering out the tasks that are not completed (completed property is false).
Your Turn
Modify the code to filter out the tasks that are not completed (i.e., completed property is false). Run the code to see the output.
What's Next?
In the next tutorial, we'll explore the find method, which is similar to filter, but returns the first matching element instead of an array of elements.
Keep coding, and don't hesitate to ask if you have any questions! 😊
Tests