I have an array of objects, I am trying to remove a specific item based on a passed argument from the user,
removeItem = (title, body){
let myArray = [
{ title : 'title 1', body: 'body of title one' },
{ title : 'title 2', body: 'body of title two' },
{ title : 'title 3', body: 'body of title three' },
]
//the problem is down here
let filteredArray = myArray.filter(item => {
item.title != title || item.body != body
}
// at this point i assume that the filtered array will not
// include the item that i want to remove
// so down here i reset the value of my original array to the filtered one
myArray = filteredArray
in simple words, the test that i am trying to run is, if either the title or the body of the user DOES NOT match a title or body in the array, put this item in a new array, therefore i will have a filtered array..
however, what happens is, the code above, removes eveything and returns an empty array.. could someone help correct the logic above ? thanks in advance
Either add return statement or remove curly brackets from the arrow function:)
myArray = myArray.filter(item => {
return item.title != title || item.body != body;
});
or
myArray = myArray.filter(item => item.title != title || item.body != body);
From MDN Filter page
callback Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:
Your callback function does not have any return keyword. By default, JS will interpret this as undefined, i.e. a non-truthy/false value. Therefore, all of your items fail to match the filter condition and you are left with an empty array.
Also, as pointed by others, you are missing a parenthesis.
let filteredArray = myArray.filter(item => {
return item.title != title || item.body != body;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With