Removing elements in common between 2 arrays

Asked

Viewed 346 times

0

I have a fixed list that contains 20 items, and I have another list that comes from the bank. I need the items I have on my fixed list to be compared to what comes from the bank and, if there are similar items, to be deleted from the list that comes from the bank.

For the better understanding:

I have the first array coming from the bank:

var array1 = [1,2,3,4,5,6]
var array2 = [1,2,3]

I mean, I want the array1 become:

array1 = [4,5,6] -- Eliminando os itens em comum com o array2.

Of course with this example I can do using filter, but with the object that comes from the bank has to compare to work and I’m not able to make this comparison.

1 answer

0


To solve your problem just use a filter combined with a includes according to the following script:

let array1 = [1,2,3,4,5,6]
let array2 = [1,2,3]

array1 = array1.filter(item => !array2.includes(item))

console.log(array1);

If you have a complex object, simply change the includes for some and check the property you want to compare, as in the following example:

let array1 = [{id:1, nome:"lalala"},{id:2, nome:"lalala"},{id:3, nome:"lalala"},{id:4, nome:"lalala"},{id:5, nome:"lalala"},{id:6, nome:"lalala"}]

let array2 = [{id:1, nome:"lalala"},{id:2, nome:"lalala"},{id:3, nome:"lalala"}]

array1 = array1.filter(item => !array2.some(item2 => item2.id === item.id))

console.log(array1)

  • 1

    Using the perfect married some, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.