My output is [2, 3, 2, 3] when it should be [1, 1] so I think I am filtering for the matching arguments rather than filtering them out. So basically I don’t understand filter, or indexOf. Or both.
function destroyer(arr) {
var convertedArr = Array.prototype.slice.call(arguments);
var targetArr = convertedArr[0];
var filtered;
function seeker(convertedArr) {
return targetArr.indexOf(convertedArr);
}
return filtered = targetArr.filter(seeker);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
filter
will remove values with a “falsy” return value from the fiter function and keep values with a “truthy” return value from the filter function.
indexOf
will return the index of the value if found (including 0
which is falsy) and -1
if it is not found (-1
is truthy).
If you want to test whether an item is present in an array using indexOf
:
arrayName.indexOf(something) !== -1 // true if something is in arrayName
Thank you for your help, I finally did it. I have to say that this has been extremely frustrating. Either I am not very good at this kind of thing, or some of these algorithms are exceptionally hard for what they have taught up to this point. Either way, once I got it I felt like crying. So, there is that.
~ Brian
PS, here is my code :
SPOILER ALERT!
function destroyer(arr) {
var convertedArr = Array.prototype.slice.call(arguments);
var targetArr = convertedArr[0];
convertedArr.shift();
return targetArr.filter(function(i) {
return convertedArr.indexOf(i) == -1;
});
}
destroyer([53, "hamburger", "tree"], "tree", 53);
1 Like
Go easy on yourself. It’s new. It’s hard. Some progressions will be more intuitive than others and sometimes you’ve hit a point where it’s time to make a jump to the next level of complexity.
2 Likes
Thank you for the encouragement. The next two algorithms went pretty well and I feel a little boost of pride and confidence.
3 Likes