Copying array with spread operator

Copying array with spread operator
0

#1

Hi,

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

Link to the challenge:


#2

oh gosh, it was easier than I tought.
it should be like this:

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


#3

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?


#4

Hi,
why we need to pass Object Array for Spread operator.

newArr.push([…arr]);

It should also work like this?

newArr.push(…arr);

I have written that in console and works fine but why codecamp is taking []


#5

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.


#6

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

#7

Yeah, that looks like it would do the trick. But if you are not using ES6, then I think slice would be better.


#8

Hey there!
I did it this way :wink: :

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