Copy an Array with the Spread Operator -- help [SOLVED]

Copy an Array with the Spread Operator -- help [SOLVED]
0

#1

Tell us what’s happening:

I checked the console, it adds the repetition into a single array but I obviously want it to spread into num of arrays. How do I do that?
Your code so far


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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator


#2

I will guide you to the solution, but you must answer my questions.

If I told you to create a literal array with the numbers 1, 2, and 3 as elements and assign the array to a variable named oneTwoThree, what is the quickest/easiest way of writing that?


#3

let oneTwoThree = [1, 2, 3];


#4

Exactly. Why not spread the contents of arr and put that inside a literal array to be pushed to newArr?


#5

By literal array you mean empty square brackets? so newArr.push([...arr])?


#6

You got it. A literal array is an array defined by the square brackets [ ].


#7

The following code:

var newArr = [];
newArr.push([…arr])

is just a shorter way to write the following:

var newArr = [];
var tempArr = [...arr]
newArr.push(tempArr)

#8

Thanks, it worked, but I still am not clear as to what have I done. Did I ask JavaScript to essentially repeat it num of times but partition the repetition into sub-arrays? Cause that was the only difference between my initial code and the solution code.


#9

Remember that the spread operator ... when applied to an array, will essentially split up the array into its elements, so wrapping the [ ] around it will put them back together in a different array without mutating the original array.


#10

Thanks, that explains it.


#12

hi, is this correct?

newArr.splice(1, 0,[…arr]);