I have done a bit of research on this topic, but I am still confused about the best way to filter an array with another array. There are two scenarios I would like to understand better. (1) The second array remains intact after filtering the first array.
Array.indexOf() will return the index of the item in the array if it is present. If it is not it will return -1.
Also make sure you understand what filter is doingβ¦ Array.filter() returns a new array containing all the items that evaluate to βtrueβ based on some criteria (ie whatever your callback function specifies). So in my example the code βsaysβ Filter array1 down to only contain the values that are not in array2 etc.
If the item in array2 is not already in array1, the function should return βtrueβ and array2 is left unmodified.
If the item in array2 is already in array1, the function should return βfalseβ and the index of the item in array1 should be located and the item removed.
In this case, two of the items in array2 (βbβ and βdβ) are already in array1, so for them βfalseβ is returned and the accompanying action is carried out (βbβ and βdβ are spliced out of array1). Item βfβ is not already in array1, so βtrueβ is returned and no action is carried out.
If array1 does not include an item from array2, the function returns true, and a new array containing the item is created. This new array is assigned to array2. In the example above, when we call array2, we now get [ 'f' ] and not ['b', 'd', 'f'].
If array1 already includes an item from array2, the function returns false. In this case, there is no accompanying action to be carried out.
If array1 includes an item from array2, the function returns true, and a new array containing the item is created. This new array is assigned to array2. In the example above, when we call array2, we now get [ 'b', 'd' ] instead of ['b', 'd', 'f'].
If array1 does not include an item from array2, the function returns false. In this example, no accompanying action is carried out. Aha!