Aniket Aniket - 7 months ago 55
Javascript Question

freecodecamp Challenges- Seek and Destroy

I am trying to solve this challenge Seek and Destroy. I can't figure out what is wrong. Any help ?

Seek and Destroy
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.

This is the initial code below:



function destroyer(arr) {
// Remove all the values
return arr;
}

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





This is my Code below:



function destroyer(arr) {
var letsDestroyThis = [];
var i =1 ; while (i<arguments.length) {
letsDestroyThis.push(arguments[i]);
i++;
}

for(var j=0 ; j< arguments[0].length; j++) {
for (var k= 0; k< letsDestroyThis.length; k++) {
if(arguments[0][j] === letsDestroyThis[k]){
arguments[0].splice(j, 1);
}
}
}

return arguments[0];
}

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





Thanks in Advance!

Answer

You can create an array of all values that are supposed to be removed. Then use Array.filter to filter out these values.

Note: Array.splice will change original array.

function destroyer() {
  var arr = arguments[0];
  var params = [];

  // Create array of all elements to be removed
  for (var k = 1; k < arguments.length; k++)
    params.push(arguments[k]);
  
  // return all not matching values
  return arr.filter(function(item) {
    return params.indexOf(item) < 0 ? true : false;
  });
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));