S.H
S.H

Reputation: 703

Pass an array and further arguments into a function. How?

I have a function which takes an array and further arguments like this: function arrayandmore([1, 2, 3], 2, 3) I need to return the array ([1, 2, 3]) without those elements which equals the arguments coming behind the array. So in this case, the returned array would be: ([1]).

One of my approaches is:

function destroyer(arr) {
  var args = Array.from(arguments);
  var i = 0;
  while (i < args.length) {
    var result = args[0].filter(word => word !== args[i]);
    i++;
  }
  console.log(result);
}

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

Console returns:

[ 1, 1, 4 ]

I don't understand, why it returns one too - I don't understand, why it does not work.

It is the same with using splice.

function destroyer(arr) {
  var args = Array.from(arguments);
  var quant = args.length - 1;
  for (var i = 1; i <= quant; i++) {
    if (arr.indexOf(args[i]) !== -1) {
      arr = arr.splice(arr.indexOf(args[i]));
    }
    console.log(arr);
  }
}
destroyer([1, 1, 3, 4], 1, 3); 

I think, both ways should work. But I don't figure out why they don't.

Upvotes: 1

Views: 75

Answers (1)

adiga
adiga

Reputation: 35202

Your while won't work because result is being overwritten in every loop. So, it only ever removes the last parameter to the destroyer function

You can use the rest parameter syntax to separate the array and the items to be removed.

Then use filter and includes like this:

function destroyer(arr, ...toRemove) {
  return arr.filter(a => !toRemove.includes(a))
}

console.log(destroyer([1, 1, 3, 4, 5], 1, 3))

Upvotes: 3

Related Questions