My code below only works for destroyer([2, 3, 2, 3], 2, 3).
function destroyer(arr) {
var isNotAnArgument = function(item){
for(var i=0;i<arguments.length;i++){
if(item === arguments[i]) {return false;}
}
return true;
};
return arr.filter(isNotAnArgument);
}
I know that arguments[0] should refer to arr but when I changed i to 1 it just made it worse. For some reason I think it’s eliminating all the elements in the array. There must be a mistake in my logic but I can’t find out where it is. Any help would be appreciated.
If you return true or false, it only checks if item passed in is equal to the first item in arguments. It will exit the loop (due to return).
Think about it this way, you don’t know how many arguments are going to be passed in. So a good way is to create an empty array myArr = []; and then loop through arguments, pushing it into myArr;
Once you have that, now you can compare all elements in myArr against elements in arr(first argument or the array). To do that, filter is actually great. You can have a function that returns the filtered array, just by using IndexOf… It looks like this:
function filterMe(value){
return myArr.indexOf(value)===-1;
}
You can then call this function with the filter method for arr:
return arr.filter(filterMe);
this should return a filtered array that passes the filterMe test on each of the items of arr.
Hopefully it makes some sense, I am, much like you, still learning.
to post code in the forum, sandwich your code in between triple backtick(```) lines like so
function destroyer(arr) {
var isNotAnArgument = function(item){
for(var i=0;i<arguments.length;i++){
if(item === arguments[i]) {
return false;
}
}
return true;
};
return arr.filter(isNotAnArgument);
}
- You are iterating through the entire argument object which includes the array itself.
- Since you used arguments inside another function, you are actually pulling in the isNotAnArguement function’s arguments as well, so the orders are not what it appears to be.
That was your main problem.
I suggest you pull argument out into an array variable and iterate through that by using
var arg=Array.from(arguments)
better yet
var arg=Array.from(arguments).slice(1)
This gives you an array of just the numbers you’re trying to match.
As the last poster pointed out, your loop is also terminating early because you have a returns inside of the loop. You also don’t need to loop through the array if all you wanted was a simple true or false of whether an array includes certain element.
Other than the indexOf method, newer browsers also support the includes function
Thanks for your input. I now realize the code didn’t work because I made many silly mistakes. It is corrected now and working fine.