Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.Js removing one item from an array using the .filter method

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

like image 815
Swilam Muhammad Avatar asked Nov 23 '25 05:11

Swilam Muhammad


2 Answers

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);
like image 121
justMe Avatar answered Nov 25 '25 20:11

justMe


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;
});
like image 35
DPac Avatar answered Nov 25 '25 20:11

DPac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!