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