Please explain for loop in Seek and Destroy

Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Seek and Destroy:

I got stumped at the for loops while trying to understand the basic code solution…

i = 0; i < arr.length of 3
j = 0; j< args.length of 8
if (arr[0]===args[0]) aka if [1,2,3,1,2,3] === [1,2,3,1,2,3]
condition is true, delete arr[0] (arr[0] becomes undefined)

j = 1;
if (arr[0]===args[1]) aka if undefined === 2

what am I missing?

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

@camperextraordinaire I did look through the code explanations. I understand the concept of the for loops but I’m not certain what the values in args actually are, and how strict comparisons work when it comes to comparing arrays.

In my above attempt to demonstrate my working steps/ understanding of the for loops, you will see that I came to a point where the first element of the array (which we’re supposed to be comparing the other elements to) is deleted. I don’t know how to proceed from there, so I think I have a misunderstanding somewhere in previous steps.

Could you (or anyone) show me how the codes would work out step by step?

Thanks!

I tried this one and it is working :

function destroyer(arr) {
//args = arr.prototype.slice.call(arguments);
args = [].slice.call(arguments);
for (var j=1;j<args.length;j++){
//for (var i=0;i<arr.length;i++)
var i = 0;
while(i<arr.length)
{
if(arr[i]===args[j]){arr.splice(i,1);
}
else i++;
}
}

return arr;
}

Why is arr = [1,2,3,1,2,3]
where has the 2 , 3 gone from destroyer([1, 2, 3, 1, 2, 3], 2, 3);

1 Like

look at the function call: destroyer([1, 2, 3, 1, 2, 3], 2, 3), there are three arguments here. But the function definition has only one parameter, so that single parameter will be the first argument, the array, the other arguments can be accessed using the arguments object: in line 4 there is this call: var args = Array.prototype.slice.call(arguments);, and in this way you get also the remaining arguments.