I'm trying to get a hang of JavaScript (again) and so far it's not going great.
The challenge:
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.
Why doesn't the code below remove the required elements for the second test case?
function destroyer(arr) {
console.log(arguments);
for (var array_i = 0; array_i < arr.length; array_i++){
for (var arg_i = 1; arg_i < arguments.length; arg_i++){
console.log("indexes", array_i, arg_i);
if (arr[array_i] === arguments[arg_i]){
console.log(arr[array_i], arguments[arg_i], "destroyed");
arr.splice(array_i, 1);
console.log(arr, arguments);
array_i = 0;
arg_i = 1;
}
}
}
return arr;
}
It successfully works here:
destroyer([3, 5, 1, 2, 2], 2, 3, 5);
But not here:
destroyer([2, 3, 2, 3], 2, 3);
array_iandarg_iwhen you delete something, but you reset them to the initial values before theforloop increment. Thus, you'll sometimes skip an element. Try resettingarray_ito-1andarg_ito0.argumentscoming from?