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.

5
  • Try this answer : stackoverflow.com/a/5072145/2570277 Commented Nov 12, 2019 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 Commented Nov 12, 2019 at 10:57
  • 1
    const result = array_data.filter((item) => !!!array.find(item2 => item2.data === item.data && item2.id === item.id)); Commented Nov 12, 2019 at 11:00
  • Thanks @hoangdv It worked. Could you please explain to me why you have used 3 not operator? Commented Nov 12, 2019 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. Commented Nov 13, 2019 at 0:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.