The filter
method (Array.prototype.filter() - JavaScript | MDN) iterates over the elements of an array. Each element in the array is passed to a function which ultimately gives a true/false answer. If the answer is true, then the element is added to a new array. If the answer is false, it is excluded. Consider the simple examples,
const numbers = [5, 2, 4, 3, 9, 5, 2, 4, 1, 4, 7, 0]
// Only even elements will pass the test (zero remainder)
// and will be included in returned array
let result = numbers.filter(num => num % 2 == 0)
console.log(result)
// [ 2, 4, 2, 4, 4, 0 ]
// Elements which are not equal to 4 will pass the test and will be included in
// returned array. Elements equal to 4 will fail the test and be excluded.
let result_2 = numbers.filter(num => num != 4)
console.log(result_2)
// [ 5, 2, 3, 9, 5, 2, 1, 7, 0 ]
I am not familiar with the exercise, so I can only make assumptions based on your screenshot. In your screenshot, favoriteRecipesReducer
has two parameters favoriteRecipes
and action
. I am assuming favoriteRecipes
is supposed to be an array of objects, whereas action
is supposed to be an object.
case 'favoriteRecipes/removeRecipe':
return favoriteRecipes.filter(element => element.id != action.payload.id);
The filter
method will iterate over the favoriteRecipes
array. In each iteration, an object from the array will be passed as the argument to the arrow function and will be assigned to the element
parameter. If the id
property of this object is different than the action.payload.id
, then the condition is true and it will be retained in the resulting array. If the id’s match, then the condition will be false and it will fail the test. Consequently, the object will be excluded from the resulting array. Consider the example,
const myArray = [ { name: "Jack", age: 17 },
{ name: "John", age: 24 },
{ name: "Jill", age: 19 },
{ name: "Lily", age: 24 } ]
let result = myArray.filter(person => person.age != 24)
console.log(result)
// [ { name: 'Jack', age: 17 }, { name: 'Jill', age: 19 } ]
// The objects whose age property was 24 are excluded.