0

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.

Aashay Amballi
  • 1,321
  • 3
  • 17
  • 39
  • Try this answer : https://stackoverflow.com/a/5072145/2570277 – Nick Nov 12 '19 at 10:54
  • 1
    If you want to remove items by id, you can use `Array.map` on your second array to get an array of ids, `const ids = array.map(e => e.id);` and then use `Array.filter` on the first one to filter out anything inside the `ids` array you must made, using `Array.includes` to test each id – TKoL Nov 12 '19 at 10:57
  • 1
    `const result = array_data.filter((item) => !!!array.find(item2 => item2.data === item.data && item2.id === item.id));` – hoangdv Nov 12 '19 at 11:00
  • Thanks @hoangdv It worked. Could you please explain to me why you have used 3 not operator? – Aashay Amballi Nov 12 '19 at 14:47
  • 1
    @AashayAmballi `.find` return `null` or a object , with 2 not operators we try to convert `something` to a boolean value, `!!null` will become `false`, if we found a object then, `!!object` ~ `true`. With final `!` , we flip the boolean value, => check if the item does not exist in `array`. – hoangdv Nov 13 '19 at 00:56

0 Answers0