DEV Community

loading...

Copying an Array with the Spread Operator

rthefounding profile image Randy Rivera ・1 min read
  • While slice() allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new spread operator allows us to easily copy all of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: ...

  • In practice, we can use the spread operator to copy an array like so:

let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
Enter fullscreen mode Exit fullscreen mode
  • thatArray equals [true, true, undefined, false, null]. thisArray remains unchanged and thatArray contains the same elements as thisArray.

  • Try it out!
    I have defined a function, copyMachine which takes arr (an array) and num (a number) as arguments. The function is supposed to return a new array made up of num copies of arr. I have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly.

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line

    // Only change code above this line
    num--;
  }
  return newArr;
}

console.log(copyMachine([true, false, true], 2));
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
newArr.push([...arr]) <----
    num--;
  }
  return newArr;
}

console.log(copyMachine([true, false, true], 2)); will display 
[[true, false, true ], [true, false, true]]
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app