Help With Javascript Reduce Method

I keep having some issues using reduce. Latest example is with Intermediate Algorithm Scripting: Seek and Destroy.

Problem

function destroyer(arr) {
  
}

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

Here’s my solution:

function destroyer(arr) {
  var args = [...arguments].slice(1)
  var newArr = arr.reduce((acc, num) => {
    if (!args.includes(num)) {
      return acc.push(num)
    }
  }, []);
  return newArr;
}

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

I always seem to run into issues with the accumulator. In this case, the error is that the accumulator is undefined.

Thanks!

The reduce function has to return the accumulator each iteration, you are not doing that, so the next time the function runs there is no accumulator.

The return value of push is the new length of the array according to MDN. The reduce method expects you to return the accumulator in the callback function, so you also need to be careful with your if statement.

One other thing to consider is if using reduce is the best method to solve this problem. What you need to do is filter the sliced arguments out of the array.

Ah, yes, that was my mistake. I updated the code so that it works.

function destroyer(arr) {
  var args = [...arguments].slice(1)
  var newArr = arr.reduce((acc, num) => {
    if (!args.includes(num)) {
      acc.push(num)
    }
    return acc;
  }, []);
  return newArr;
}

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

Note that your original code would have worked had you used concat instead of push.