How can I make it num times copy of the array?
Here is my code:
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// change code below this line
newArr = [...arr] *num;
// change code above this line
num--;
}
return newArr;
}
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));
I would say that you don’t need the *num - the while loop will take care of that.
So, you are creating a copy of arr with the spread operator - [...arr]. Good, you are doing that correctly. So, how do you add that new array copy to newArr? I can think of two ways - one using the push method and one using the spread operator again. I think the first method is more direct. Do you know how to add an element (in this case an array itself) to an array using the push method?
Those are two different things. The second one is spreading the elements in arr and pushing them each into newArr as separate elements. The first is wrapping all of those arr elements in an array and then pushing that one array onto newArr. There is a big difference there. It depends on what you want the contour of your data to look like.
“works fine” is relative. Yes, it does not cause an error, but does it do what the test required? It does something but is it the right thing.
Hi, just wondering one thing, apart from the test’s requirement,
does this code work fine as well?
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));
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// change code below this line
newArr[num-1] = [...arr]
// change code above this line
num--;
}
return newArr;
}
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));
Hey, just wanted to share my solution.
Given the hints, this is what i came up with.
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// change code below this line
let obj = [...arr];
newArr.push(obj)
// change code above this line
num--;
}
return newArr;
}