Ad
  • Custom User Avatar

    This helped me as well. Thank you for the explanation. I ended scrapping the the use of splice() simply becuase i couldnt figure that out. ended up just deleting the element in the list using delete and using filter to filter out falsy values that were not === 0 till i got what was needed. This was helpful to understand though. Thanks again

  • Custom User Avatar

    It is clear that the i-- is needed from the test case where a=[1,2,2] and b=[2]. In this case array.a has a length of 3 and the function will loop through array.a checking for a match with array.b at index 0, then index 1, then index 2. So what happens is the loop finds no match when it checks against index 0 (because a[0]=1), then the loop finds the first match when it checks against index 1 (because a[1]=2) and splice removes this value. However doing so modifies the length of array.a! array.a now looks like a=[1,2] which has a length of 2, comprising index 0 and index 1. But your loop has already checked index 0 and index 1, so the loop will now terminate. By removing the value of a[1] in your loop you have now moved the value which was at a[2] into the position of a[1] in the array. And now you need to make sure you loop checks this new value. So you have to reduce the loop count by 1 (i--) so that it will check the same index in the array again to see if the new value is also a match.

    tl;dr Without the i-- (which just decrements/decreases the value of i by 1) what happens is you loop through array.a and it finds a match at a[1], moves value a[2] into a[1] and does not check a[1] again. You need it to perform this check to be correct.

  • Default User Avatar

    After struggling for a while I looked at your solution. Mine was exactly the same except I was missing 'i--' and so couldn't delete all instances of b from a. Still not sure I understand how 'i--' allows you to remove them all. Could you explain? Thanks