0
function destroyer(arr) {
  const newArr = [...arguments[0]]
  for(let i = 0; i < newArr.length; i++){
    for(let j = 1; j < arguments.length; j++){
      if(arguments[j] == newArr[i]){
        newArr.splice(i,1)
        console.log(newArr)
      }
    }
  }
}

destroyer([3, 5, 1, 2, 2], 3, 5, 2);

New JS learner here.

Working on a problem that is supposed to look through the first arg in destroyer which will be an array and remove the elements that match the arguments following the array.

Results are [1,2] in the console output. Intended results are [1] with the given parameters Upon further testing it seems like the destroyer function is only removing the first instance of any value that it matches in newArr. If I take the second instance of '2' out of the test set it behaves as intended. I'm trying to understand what in my logic here is wrong. I've tried several different iteration patterns and can't seem to see what the problem is.

Thanks for any help!

4 Answers4

0

I am going to link a few other answers here is this seems to be a fairly common question. The gist is that you are iterating over the live array while removing items from that array resulting in potentially skipping items.

Alternatively you could also the filter method to help remove multiple values:

Poiuy
  • 331
  • 2
  • 6
0

Try this:

function destroyer(arr) {
  const newArr = [...arguments[0]]
  for(let i = newArr.length - 1; i >= 0; i--){
    for(let j = 1; j < arguments.length; j++){
      if(arguments[j] == newArr[i]){
        newArr.splice(i,1)
        console.log(newArr)
      }
    }
  }
}
0

This is an array pointer issue.

when i = 3 and j = 3, the function will match arguments[3] == newArr[3]. At this moment, newArr will be removed 1 element which is the first 2, and then the newArr becomes an new array that is [3,5,1,2].

The next index i is 4 which doesn't exist in the new newArr. So, the function will return and finish. That's why you get [3,5,1,2].


function destroyer (arg) {
    if(!Array.isArray(arg)) return arg;
    return arg.filter(x => !Array.prototype.slice.call(arguments, 1).includes(x))
}
Sam
  • 91
  • 4
0

It is because newArr is getting shorter as you splice it through your loops and the loop itself is also shortened.

see this probably your solution

baihakhi
  • 41
  • 5