0

Trying to figure out the proper syntax on filtering elements out of one array if they belong in another but can't get it right. In the following example I'm trying to remove any elements in array1 that are in array2. Any ideas on how to make it work?

array1.filter( element => array2.includes( element ) ); 
  • 2
    So you want to keep any element that is not in the 2nd array - `!array2.includes( element )`. Note the not (`!`) sign. – Ori Drori Sep 20 '21 at 20:45
  • Yeah exactly. I tried that before but it didn't work. I must be doing something else wrong. – nothing special Sep 20 '21 at 20:49
  • What type of elements are you dealing with? Non primitives are not identical, even if they look the same, and have the same properties - `{ a: 1} !== { a: 1 }`. – Ori Drori Sep 20 '21 at 20:50
  • They are both Arrays of Strings so what you recommended should work so something weird is going on here. I even have a push happening right before it and that works fine. – nothing special Sep 20 '21 at 20:56
  • 1
    Got it working. I was console logging the array filter. I needed to assigning the filter to the array by adding array1 = before it. The not operator works just fine now. Thanks ! – nothing special Sep 20 '21 at 21:11

1 Answers1

2
array1.filter( element => !array2.includes( element ) ); 
mouafus
  • 148
  • 7