I have a general question on the array filtering. It might be a repeated question also.
Consider If I have an array:
const array_data = [
{ id: 1, data: "some data" },
{ id: 2, data: "some data" },
{ id: 3, data: "some data" },
{ id: 4, data: "some data" },
{ id: 5, data: "some data" }
];
and if I have an array of objects which I want to remove from array_data for example:
const array = [{ id: 2, data: "some data" }, { id: 5, data: "some data" }];
and the final array should be
[
{ id: 1, data: "some data" },
{ id: 3, data: "some data" },
{ id: 4, data: "some data" }
];
How can I get that final/result array without mutating the original array_data.
Array.mapon your second array to get an array of ids,const ids = array.map(e => e.id);and then useArray.filteron the first one to filter out anything inside theidsarray you must made, usingArray.includesto test each idconst result = array_data.filter((item) => !!!array.find(item2 => item2.data === item.data && item2.id === item.id));.findreturnnullor a object , with 2 not operators we try to convertsomethingto a boolean value,!!nullwill becomefalse, if we found a object then,!!object~true. With final!, we flip the boolean value, => check if the item does not exist inarray.