Intermediate Algorithm Scripting - Seek and Destroy

Tell us what’s happening:
Describe your issue in detail here.
I’ve solved this problem with some help of the hints but don’t understand how the function can take in multiply arguments if there’s only one parameter? Is this just a function of how Arguments work or have functions always been like this?

  **Your code so far**
function destroyer(arr) {
const valuesToRemove = Object.values(arguments).splice(1);
const localArr = [];
for (let i = 0; i < arr.length; i++){
  let removeValue = false;
  for (let j = 0; j < valuesToRemove.length;j++){
    if (valuesToRemove[j] === arr[i]){
      removeValue = true;
      }
    }
  if (!removeValue){
    localArr.push(arr[i]);
  }
}
console.log(localArr)
return localArr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Seek and Destroy

Link to the challenge:

in JavaScript the number of parameters and arguments doesn’t have to match, the arguments object is one way to deal with a variable number of arguments

2 Likes

I may be stating the obvious here but don’t write functions like this – as you are discovering it’s really unclear.

The challenge is there to get you to understand that JS functions can take any number of arguments, and understanding how to deal with that. That’s important – it’s how JS works and has always worked. But IRL it’s unusual to hide function arguments, makes the code very hard to follow.


Following syntax is introduced at a later point, so don’t worry about it now, but normal way to show a function takes many arguments is like this:

function addNumbers(...numbers) {

Which uses the rest operator ..., and where ...numbers means “any number of arguments, which you can access inside the function as an array called numbers”, so:

function addNumbers(...numbers) {
  let total = 0;
  for (let number of numbers) {
    total += number;
  }
  return total;
}
console.log(addNumbers(1, 2))
// 3
console.log(addNumbers(1, 2, 3))
// 6
console.log(addNumbers(1, 2, 3, 4, 5, 6))
// 21

As applied to this challenge, the function declaration would look something like this:

function destroyer(arr, ...targets) {

As I say though, don’t worry about it atm, there are sections on using the ... operator to come

2 Likes