Seek and Destroy // some problem with my code

Seek and Destroy // some problem with my code
0

#1

Tell us what’s happening:
Hi everyone,

I guess this code is not the best option, but I was wandering if it’s possible to solve this problem via using this method. It is not working for some reason and I want to know why - if possible, please explain this to me (if it’s workable at all).

``````function destroyer(arr) {
// Remove all the values

for (var i = 0; i < arr.length;i++){
var firstElement = arr[0];
for(var j =1; j < arr.length;j++){
var otherElements = arr[j][0];
}
for(var k = 0; k < firstElement.length;k++){
var newArr = [];
if (firstElement[k]!==otherElements){
newArr.push(firstElement);
}

}
}
return newArr;
}

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

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36`.

#2

First of all, the arr variable refers to the array [1, 2,3, 1, 2, 3]. When you write the following, you are assigning the value 1 to firstElement every iteration of the outer for loop.

``````var firstElement = arr[0]; // always will be the value 1
``````

The first nested for loop (shown below), you attempting to reference a property called “0” on each of arr’s elements and assign it to otherElements. There is no such property, so you get undefined assigned to otherElements in each iteration.

``````    for(var j =1; j < arr.length;j++){
var otherElements = arr[j][0];
}
``````

This code is not the correct algorithm. I suggest you write out an algorithm for this challenge and test it by walking through the test case with your algorithm steps to see if you would arrive at the correct answer. If you need help writing an algorithm, first post your attempt at writing out the steps in plain language or pseudo-code. That way, we can understand how you are thinking about the challenge and can give you hints about how you might approach it differently.