In JavaScript there are at least 5 different ways!! to duplicate an array. I always optimize for developer-friendliness but if you care about the performance of these different approaches, know that real-world speed will vary depending on the most recent browser builds.

The simplest way to duplicate an array in 2018 is to use the ES6 spread operator. Previously using slice() was probably the best approach. You can still use concat though the approach isn’t as clean in my opinion, and Array.from is a fun way to do it, too, just for kicks.

Finally, if you’re told to duplicate an array without using a built-in method then you can still accomplish it with a basic for loop.

const arr = [1,2,3,4,5];

// Spread Operator  
const arr1 = [...arr];

// Slice Operator
const arr2 = arr.slice();

// Concat
const arr3 = [].concat(arr)

// Array.from()
const arr4 = Array.from(arr);

// For loop
function arr5(arr) {
  let newArr = [];
  for(let i=0; i<arr.length; ++i) {
      newArr[i] = arr[i];
  }
  return arr;
}

Note: All of the above are shallow copies. If the original array is multi-dimensional there will be problems since you need a deep copy.

You can solve this by serializing the entire array to JSON and then de-serializing it, but this results in bad performance and doesn’t work with special objects.

// Deep copy
const dupArray = JSON.parse(JSON.stringify(arr))




Want to improve your JavaScript? I have a list of recommended JavaScript books.