Home > Mobile >  How can i target elements in another array via .filter()
How can i target elements in another array via .filter()

Time:08-11

Im trying to return the values in argument[0] that are not equal to the values of arguments[1] and so on.

Ive created a variable 'let argArr' that holds the values of the arguments after the first, Im trying to understand why in my .filter() i cannot target 'let argArr'?

function destroyer(arr) {
  let argArr = [];

  for (let i = 1; i < arguments.length; i  ) {
    argArr.push(arguments[i])
  }

  return arr.filter(i => i !== argArr)
}

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

CodePudding user response:

You are comparing an arr array's element to the argArr what is wrong. The right way is to check if element is inside argArr and filter if yes.

return arr.filter(i => !argArr.includes(i))

CodePudding user response:

Instead of using arguments explicitly specify the array as the first argument, and then use rest parameters to gather all the remaining arguments into an array. Then use filter to return only those elements in the array that are not in the rest array.

function destroyer(arr, ...rest) {
  return arr.filter(el => !rest.includes(el));
}

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

CodePudding user response:

Use spread operator to treat arguments as normal array

function foo() {
    return [...arguments].filter(el => el);
}
console.log(foo(1,2,3))

  • Related