Proposal of possible solutions for " Copy an Array with the Spread Operator" challenge

Tell us what’s happening:
Describe your issue in detail here.

Not quite sure what pros of this solution “newArr.push([…arr]);”

As soon we copied array, not values, it could be shorten to: “newArr.push(arr);”, i.e. spread here have no point here.

Since this challenge teach us for spread, doesn’t it would be better if we use only spread here to copy, like in my solution?

P.S. Sorry if wrong topic, I didn’t find any 'feedback for challenge ’ .

  **Your code so far**
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
  // Only change code below this line
  newArr = [...newArr, arr];
  // Only change code above this line
  num--;
}
return newArr;
}

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/103.0.0.0 Safari/537.36

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

I’m not sure what you are saying here. There is a big difference between those two.

const newArr1 = []
const newArr2 = []

const arr = [1, 2, 3]

for (let i = 0; i < arr.length; i++) {
  newArr1.push([...arr])
  newArr2.push(arr)
}

console.log(JSON.stringify(newArr1))
// [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

newArr1[0][0] = 'Howdy!'

console.log(JSON.stringify(newArr1))
// [["Howdy!", 2, 3], [1, 2, 3], [1, 2, 3]]



console.log(JSON.stringify(newArr2))
// [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

newArr2[0][0] = 'Howdy!'

console.log(JSON.stringify(newArr2))
// [["Howdy!", 2, 3], ["Howdy!", 2, 3], ["Howdy!", 2, 3]]

The solution you offer would have the same issue.

Keep in mind that the solutions are not maintained - personally I wish we’d get rid of them. That being said, the solution does solve this challenge the way it was intended to be solved. Note that the test says, “The copyMachine function should utilize the spread operator with array arr” - for me that removes all ambiguity.

I agree that the challenge is not worded particularly well - it is not clear to me why we need to use the spread operator - not without using my experience, anyway.

Yeah, I totally missed this ‘drop reference’ part, my bad…
newArr = […newArr, […arr]]; - in that case (I just was confused by mix of .push() and spread)

Ok, got it, np.

Thanks for response.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.