Hi,
I’m working on the Seek and Destroy algorithm, but there’s one thing I don’t understand.
Here’s my solution (which works):
function destroyer(arr) {
var args = Array.from(arguments);
for (var i = 0; i < arr.length; i++) {
for (var j = 1; j < args.length; j++) {
if (arr[i] === args[j]) {
delete arr[i];
}
}
}
return arr.filter(Boolean);
}
Here I use j = 1
to iterate through the arguments, except the first one which as far as I understand is the same as arr
.
But I saw other solutions that have j = 0
and the algorithm also works. I don’t understand this because in the first time we run the for
loop it will compare arr
with args[0]
, which are both [1, 2, 3, 1, 2, 3]
. Therefore, all the elements in arr
should be deleted.
Could anyone help me understand why this solution (with j = 0
) is also correct?
Thanks