For loop inside filter method

I want to remove from numArr1 34 and 67, which are shared by two arrays.
But my code doesn’t do the job.
When !== is changed to ===, it returns [34, 67], which I was expected. But !== just doesn’t work. Could anyone help me, please.

let numArr1 = [23, 56, 14, 34, 45, 67]
let numArr2 = [11, 34, 78, 67, 28, 99]

let newArr = numArr1.filter(num =>{
  for(let i = 0; i < numArr2.length; i++){
    if(num !== numArr2[i]) {
      return num;
    }
  }
})

console.log(newArr);
1 Like

.filter() creates a new array, do you know how filter determines if an element should be added to this new array?

1 Like

Check if each element meets the condition and if it does, it gets included in the new array?

close, filter constructs a new array of all the values for which callback returns a value that coerces to true.

this is important, because positive integers are truthy/coerces true.

once a function reaches a return keyword, a function ends:

function example(){
  for(let i = 0; i < 10; i++){
    console.log(i);
    return i
  }
}
example()

as you can see, the loop only makes a single iteration (due to the return keyword in the loop)

this is also your problem, the for loop will stop the callback way to early, and filter will continue to the nest callback.

the better approach would be to check if num === numArr2[i], if so, return false (because you don’t want to include it the newly constructed array). So the condition can still evaluate to true, but we return false to exclude the value from the newly constructed array.

you also have to return true for values you want to include in the newly constructed array, but i will leave that for you to figure out. No fun if i spoil everything

hope this helps

1 Like

Thank you for your reply.

this is also your problem, the for loop will stop the callback way to early, and filter will continue to the nest callback.

Is this what you mean?
Every element in numArr1 is passed into the callback against numArr2[1] (=11), then the filter loop moves to a next element in numArr1 because it always returns true (none of the elements is not 11) instead of passing the element into callback against numArr22?

1 Like

yes, that is what i mean

the for loop only makes a single iteration in each callback execution, because in the first iteration of the for loop, true is returned, ending the callback execution, so filter will add the item and move on to the next callback execution.

1 Like