Please explain for loop in Seek and Destroy

Please explain for loop in Seek and Destroy
0

#1

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?


#2

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.


#3

If you look below the solution, there is a very detailed explanation on how the basic solution works. Did you read it first?


#4

@RandellDawson 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!


#5

OK. Below is the basic solution with added console.log statements, so you can see the values of various variables as the code executes. I used the first test case in the call to the function. It is better to open up the solution on the repl.it site so you can see the console results easier.


#6

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;
}