What is the intended solution for Copy an Array with the Spread Operator?

Basic Data Structures: Copy an Array with the Spread Operator

I got the tests to pass but I feel like i’m not supposed to do it the way I did.

At first I got all of the test to pass except the one that requires you to use the spread operator with just this:

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // change code below this line
    newArr.push(arr);
    // change code above this line
    num--;
  }
  return newArr;
}

And to get the last test to pass I just did a useless spread of the array in the push method

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // change code below this line
    newArr.push([...arr]);
    // change code above this line
    num--;
  }
  return newArr;
}

What is the intended solution for this problem that makes use of the spread syntax in a way that is actually needed and useful? Is it a lot cleaner than just appending the passed arr to the end of newArr on each iteration of the loop?

It looks like the intended solution is exactly what you’re doing in your second example. Probably just a bad example in the challenge, if you want open a github issue to let them know.

I came up with this:

newArr = [...newArr, arr];

It’s pretty useless in this example and it doesn’t pass the test too. But it’s good to know because you use it a lot when dealing with immutability, like in redux for example.

1 Like

I feel like your solution is the kind of thing I expected this challenge wanted. It surprises me that it doesn’t pass the tests and I wonder why they want the spread to be on the passed in array arr.

I’m just curious. Why does this work

newArr.push([…arr]);

but this does not

newArr.push([arr]); ?

Isn’t the second just appending the arr to the newArr as well?
I know is required to complete the challenge, but I can’t pass any tests at all with the second solution from above.

Thanks for the help!

The 2nd option you listed above is simply wrapping around arr array inside of a new array. It’s created a new array.

The 1st option is you are spreading arr into comma separated values so this will effectively create a new array with values of arr.

1 Like