Basic Data Structures - Copy an Array with the Spread Operator

Tell us what’s happening:
Describe your issue in detail here.
Hi,

tried my code, it seems to produce the array ‘num’ times as asked but the I keep getting an error that its not correct.

Could you please help me understand what I am doing wrong?

thanks

Your code so far

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

console.log(copyMachine([true, false, true], 3));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Basic Data Structures - Copy an Array with the Spread Operator

Link to the challenge:

The problem is on this line:

newArr[num] = [...arr];

The code above will copy all of the elements into newArr but will also reinitialise newArr with every new iteration of the while loop.
You are iterating on the array elements and assigning them and then you assign all the elements on the array to newArr
The solution is:

newArr.push([...arr]);

The spread operator copies all elements into a new empty object and push will add the elements to the array

It should work if you subtract 1 from num when using it for the array index.

newArr[num - 1] = [...arr];

Remember that arrays use zero-based indexes.

Thanks a lot @cesar.ochoacalvillo for the response. I tried using ‘push’ earlier but I was making a mistake by using:
newArr =newArr.push([arr])

and it was giving me an error.

Tried it your way and it works.

I have also tried using:
newArr[num - 1] = […arr];

and it works.

Thanks

Thanks a lot @lasjorg .

I have tried:
newArr[num - 1] = […arr];

and it works.

thanks,

Ala

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.