'filter operator explained step by step
function deleteTask(id) {
const remainingTasks = tasks.filter((task) => id !== task.id);
setTasks(remainingTasks);
}
Ijust want to know in plain english, as if I was a 5 years old, what is going on here, step by step?
Solution 1:[1]
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Here is what is going on in that code, step by step:
deleteTask
is called with paramterid
filter
loops through each element of thetasks
array, and checks if the conditionid !== task.id
istrue
- If the condition is
true
, the element is added to the new array calledremainingTasks
- The new array
remainingTasks
is saved to state
See below for an example of the filter() method:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
The setTasks
function is part of the React useState
hook. useState docs.
Solution 2:[2]
The filter function takes in another function as a parameter and returns an array as its result. This function is then run on every element in the specified array (myArray.filter
). The passed in function should return a boolean value (or something else that evaluates to truthy or falsy). If the returned value for an element is truthy, it will be included in the return array of filter
. If the returned value for an element is falsy, it will be filtered out, hence the name.
Your code example takes in an id, goes over every task in an array and checks filters out every element with the passed in id. Afterwards it uses the filtered array to update the state.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pez |
Solution 2 | Nils Fahle |