1

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.

5
  • so return the array excluding all the elements appearing in the arguments of the function? Commented Feb 4, 2019 at 12:39
  • 4
    Use the rest operator. destroyer(arr, ...rest). Then you have two arrays which you can filter through. Commented Feb 4, 2019 at 12:39
  • 2
    Something like this? const diff = (a, ...b) => a.filter(v => !b.includes(v)); Commented Feb 4, 2019 at 12:40
  • what should be the output of destroyer([1,1], 1)? Does an element need to appear twice to remove 2 elements from the list? Commented Feb 4, 2019 at 12:40
  • 2
    Yoshi gave a better solution, but if you want to know why yours doesn't work, you restart the value of result on every iteration. You could start it before the loop (result = arr[0]) and then update it in the loop, (result= result.filter(...).) Commented Feb 4, 2019 at 12:43

1 Answer 1

3

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))

Sign up to request clarification or add additional context in comments.

1 Comment

fyi, the ... you're using is the rest operator, not the spread operator. the rest operator collects all elements into an array, whereas the spread operator allows iterables to be expanded into single arguments/elements.

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.