* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
1.1 KiB
1.1 KiB
title
title |
---|
Copy an Array with the Spread Operator |
Copy an Array with the Spread Operator
Hints
Hint 1
- The final hint in the example tells you to use a recently learned method.
Hint 2
- The spread operator copies all elements into a new empty object.
while (num >= 1) {
newArr = [...arr]
num--;
}
- The code above will copy all of the elements into
newArr
but will also reinitialisenewArr
with every new iteration of the while loop. - A new variable should first be initialised using the spread operator -
let obj = [...arr];
- then this variable should be added to thenewArr
for every iteration of the while loop.
Solutions
Solution 1 (Click to Show/Hide)
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;
}
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));