0

This is the question Prompt:

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.

This is the model solution:

function destroyer(arr) {
  let valsToRemove = Object.values(arguments).slice(1);

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < valsToRemove.length; j++) {
      if (arr[i] === valsToRemove[j]) {
        delete arr[i];
      }
    }
  }
  return arr.filter(item => item !== null);
}

My question is: why must we assign to “valToRemove” “Object.values(arguments).slice(1)” and not “arr.slice(1)”

VLAZ
  • 18,437
  • 8
  • 35
  • 54

1 Answers1

3

Look at the definition again:

an initial array (the first argument in the destroyer function), followed by one or more arguments

So arr is "an initial array (the first argument in the destroyer function)"

Object.values(arguments).slice(1); is "followed by one or more arguments"


If you sliced arr then you might as well just say:

 function destroyer(arr) {
     return arr[0];
 }

… which is very different.


That said, the modern approach to this would be to use rest parameter syntax:

function destroyer(arr, ...valsToRemove) {
VLAZ
  • 18,437
  • 8
  • 35
  • 54
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 1
    The more I look at `Object.values(arguments).slice(1)` the weirder it is to me. OK, so the solution didn't use rest syntax - but why not `[...arguments].slice(1)` as it's a lot more natural to write? Or even the older style `Array.prototype.slice.call(arguments, 1)`. Getting the values then slicing seems very odd, honestly. – VLAZ Mar 29 '21 at 17:13
  • 1
    @VLAZ — Presumably because spread syntax is (relatively) new and shiny and the person who wrote the model answer didn't know about it or wrote it before spread syntax was well supported. – Quentin Mar 29 '21 at 17:14
  • 1
    I guess that makes the most amount of sense. It was written in the ES6 transition period. – VLAZ Mar 29 '21 at 17:15
  • Thanks everyone, much appreciated – Bassam Addas Mar 29 '21 at 17:23
  • @Quentin what gets me is that `Object.values` is a ES2017 feature. The rest syntax predates it – evolutionxbox Mar 29 '21 at 23:08
  • @evolutionxbox it was available way before 2017. – VLAZ Mar 30 '21 at 04:52