Tell us what’s happening:
My solution works for 1,2, & 5, but not 3 & 4. I have no idea why it doesn’t work, any help would be greatly appreciated.
Thanks
Your code so far
function destroyer(arr) {
var args = Array.from(arguments);
for (var i = 0; i < arr.length; i++) {
for (var j = 1; j < args.length; j++) {
if (arr[i] === args[j]) {
arr.splice(i, 1);
}
}
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/seek-and-destroy
Thanks, I gave up on splice / slice and instead made a new array of unique items through a couple loops. This took me forever to figure out (learning to start the args loop on 1 and how to check each letter against all the args was the tricky part for a noob) and I didn’t like the spoiler answer because I would have never used filter(bool) or delete based on what I could discover on my own. Here’s my eventual basic solution:
function destroyer(arr) {
var args = Array.from(arguments);
var newArray = [];
for(var i = 0; i < arr.length; i++) {
for (var j = 1; j < args.length; j++) {
if (arr[i] !== args[j] && j == args.length-1) {
newArray.push(arr[i]);
} else if (arr[i] !== args[j] && j < args.length-1) {
continue;
} else {
break;
}
}
}
return newArray;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Glad you figure out a solution!
FYI - For your original solution, you just needed to decrement i by one after the splice.
function destroyer(arr) {
var args = Array.from(arguments);
for (var i = 0; i < arr.length; i++) {
for (var j = 1; j < args.length; j++) {
if (arr[i] === args[j]) {
arr.splice(i--, 1); // the i-- backs up i by one to account for the shift of everything to the left
}
}
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
1 Like