Help with the Seek and Destroy algorithm

Hello,
I managed to write a working code for the Seek and Destroy algorithm, but as i saw other solutions my code is a bit messy and poorly written compared to them:

function destroyer(arr) {
   var finalArr = [];
var argArr = [].slice.call(arguments);
var target = argArr.shift();
var test = argArr.slice(0);
finalArr = target.filter(function(item) {
if (!test.includes(item)) {
       return target.slice(item);
     } else {
       finalArr.push(item);
     }
   });
  return finalArr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Could someone please help me to refactor this code, because even i don’t really understand every piece of it, how it works and passed the test.
Thanks :slight_smile:

Oh sorry corrected the spoiler tag.

What i don’t understand is the IF statement at the end.

My original code was: if (test.includes(item) so when the item is included in the test array, slice the item “out” (don’t put it to the finalArr) and when it’s not included in the test than add it to the finalArr, and at the end give back the finalArr.

This code was wrong because it gave back the opposite what i wanted so i just added the ! to the if statement. However i don’t understand why the ! was needed for the algorithm to pass.

Thank you for your help, and forgive me if im asking a banal question.

Here’s my 2 cent breakdown.

So target held [1,2,3,1,2,3] after the shift. This is what we will be filtering. the test variable is actually unnecessary as it will hold [2,3], which is what argArr is now holding after you shifted the first index item out, but that is minor.
finalArr will hold the items filtered out based on the function’s boolean value being true or false. So, if test (which is [2,3]) includes item (each item in target ie [1,2,3,1,2,3] one at a time) we have a true result which pushes the item into the final array for us. Now you had to use ! to indicate that if test DID NOT include the item, it would push the item into the array. So when item is 1, test [2,3] does not include (or have present) a 1 inside it, so the 1 gets pushed to the finalArr.

Here is what I did:

function destroyer(arr) {
  var args = Array.prototype.slice.call(arguments);
  var tempArr=args.shift();
  var final=tempArr.filter(function(temp){
    return !args.includes(temp);
  });
  return final;
  
}

Matt

Thanks very much Matt! I read your explanation and went through the JS basics again so it’s all clear now. :slight_smile:

1 Like