So I’ve done the challenge Seek and Destroy in the basic algorithm scripting challenge. It asks me to destroy numbers from an array if that numbers are given to the function.
So what I created:
function destroyForProfit(arrOne, arrTwo){
for (var i = 0; i < arrOne.length; ++i){
for (var j = 0; j < arrTwo.length; ++j){
if (arrOne[i] === arrTwo[j]){
arrOne.splice(i,1);
}
}
}
return arrOne;
}
function destroyer(arr) {
// Remove all the values
var clayArray = [];
var arrOne = [];
var arrTwo = [];
for(var i = 0; i < arguments.length; ++i){
clayArray[i] = new Array(1);
clayArray[i] = arguments[i];
arrOne = clayArray[0];
arrTwo[i] = clayArray[i];
}
arrTwo.shift();
arrOne = destroyForProfit(arrOne, arrTwo);
arrOne = destroyForProfit(arrOne, arrTwo);
return arrOne;
}
I’m happy to say that it works. The question I have is that I dont know why I have to go through destroyForProfits TWICE (or more)? If I go through the function once, it doesn’t work. Can somebody explain to me why and what I did wrong?
This is the text provided by the challenge (so you guys may not have to look it up):
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
destroyer([2, 3, 2, 3], 2, 3) should return [].
destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].