Filter question

Tell us what’s happening:

It seems like this code should only pass the challenge if it filters out what is included in removeVals that also exists in arr. It looks like the code is saying, “filter out of arr what is not included in removeVals”. The code passes the challenge but I don’t get it. Thanks for helping me understand this.

  **Your code so far**
function destroyer(arr, ...removeVals) {
return arr.filter(elem=>!removeVals.includes(elem));
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

Challenge: Seek and Destroy

Link to the challenge:

Filter keeps anything that returns true for the provided function

1 Like

@DanCouper Thanks for your concise way of helping me understand.

If filter only keeps what returns true for the provided function then what’s going on with Intermediate Algorithm Scripting challenge “Diff Two Arrays”?
The answer below solves the challenge with “strictly equal” but if filter keeps what returns true in it’s function, why would the diffArray function below return 4 when to me it seems like an array of everything besides 4 should be returned since 4 isn’t “strictly equal” to any of the other numbers in the combined array.

function diffArray(arr1, arr2) {
  const arr1and2 = arr1.concat(arr2);
  return arr1and2.filter(elem => arr1and2.lastIndexOf(elem)  === arr1and2.indexOf(elem));
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

The instructions for Diff Two Arrays says:

“Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both.”

Since 4 is the only number not found in both of the arrays then diffArray should return [4].

1 Like

You’re right. I’m just trying to find out why “strictly equal” in the context of the code I used to solve Diff Two Arrays doesn’t cause filter to return an array of every number instead of 4. According to @DanCouper " Filter keeps anything that returns true for the provided function".

"make a new array by adding by sticking the contents of arr2 on the end of arr1"

“filter out every element where the index of the first occurrence of the element is not the same value as the index of last occurrence of the element”

1 Like

What factors decide whether filter “filters out” or “keeps” what returns true for its provided function? @DanCouper said, " Filter keeps anything that returns true for the provided function" but you are saying that filter in the context of Diff Two Arrays filters out what returns true for its provided function.

I most certainly am not.

This is the same thing as saying

"retain every element where the index of the first occurrence of the element is the same value as the index of last occurrence of the element”


You seem to be struggling with boolean logic. It might be worth doing some research on the topic.

1 Like