Sum All Primes Solution 4 Filter

Up to this point I’d thought I knew how filter worked, but the filter used in solution 4 seems to be more complicated. I’m trying to understand how filter is able to get rid of number 4 in the nums array while keeping everything else in the array. Would be awesome if someone could explain that for me :smiley:

let nums = [2,3,4,5]

for (let n in nums) {
     nums = nums.filter(val => val == nums[n] || val % nums[n] != 0); 
}

the loop will iterate over the array, so the value of nums[n] change at each iteration
so the first one is 2
now, the val parameter of the callback will be each number in the array one by one
now it compares the two using val == nums[n] || val % nums[n] != 0
val is 2 - 2 == 2 is true, so 2 is kept
val is 3- 2 == 3 is false, but 3 % 2 != 0 is true so 3 is kept
val is 4 - 2 == 4 is false, and 4 % 2 != 0 is false, so 4 is not kept
val is 5 - 2 == 5 is false, but 5 % 2 != 0 is true, so 5 is kept

now nums is [2, 3, 5]
and the loop will go to a new iteration with a new value of n

after this there aren’t other values removed as it will always return true one way or an other

1 Like

Thx for you explanation!!! That makes a lot of sense now xD