0

I want this function to work and produce the array [1,1], why doesn't it work?

 function destroyer(arr) {
      return arr.reduce(function(a,b){
         if (arguments.slice(1).every(function(arg){
             return arg !== b;
         })) a.push(b);
         return a;
      }, []);
    }

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
2
  • What does it produce instead, and why do you think it should return [1,1]? Commented Aug 6, 2015 at 23:24
  • function destroyer(arr) {var args = Array.prototype.slice.call(arguments, 1); // Save arguments in a closure return arr.reduce(function(a,b){ if (args.every(function(arg){ // Access them here return arg !== b; })) a.push(b); return a; }, []); } Thanks to Jan for clearing things up as well. Commented Aug 7, 2015 at 0:01

2 Answers 2

3

I suggest

function destroyer(arr) {
  return [].slice.call(arguments, 1).reduce(function(arr, num) {
    return arr.filter(function(item) {
      return num !== item;
    });
  }, arr);
}

Or, in ES6,

function destroyer(arr, ...unwanted) {
  return unwanted.reduce((arr,num) => arr.filter(item => num !== item), arr);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is of course much nicer, but it doesn't answer OP's question "why doesn't it work?"
To note, using slice on arguments will prevent the V8 engine from optimizing.
0

jsFiddle Demo

arguments is not an array. It is "array-like". You need to call the array prototype. Also, splice modifies the array each time it is called, so it should only be used once.

function destroyer(arr) {
  //access the array prototype,
  //splice first element off of argument array,
  //and store result
  var args = [].splice.call(arguments,1);
  return arr.reduce(function(p,c){
   //indexOf is an easy way to look for existence in an array
   if( args.indexOf(c) == -1 ) p.push(c);
   return p;
  }, []);
}

Calling this on your input, destroyer([1, 2, 3, 1, 2, 3], 2, 3) will result in [1,1].

1 Comment

Gotcha, was not aware that arguments is not technically an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.