Copying Arrays

We are continuing to explore the JS ... and how to copy arrays.


The spread operator ... is fraught with complexities when trying to copy arrays. Personally, I stick with many of the tried and true array methods: slice(), splice(), shift(), unshift(), pop(), etc.

The Old Way

var coffee = ['cream', 'sugar', 'water', 'beans'];
// index value  0        1        2        3

// slice() takes two optional parameters

// omitting both will copy the entire array
var joe = coffee.slice(); // ['cream', 'sugar', 'water', 'beans']

// just using one param tells where to start copying the array
// REMEMBER zero-based counting
var joeSweet = coffee.slice(1);     // ['sugar', 'water', 'beans']

// including the second param, tells where to stop in the array
// (AND don't include the ending count element) 
var sweetWater = coffee.slice(1,3); // ['sugar', 'water']

// using a negative index sets the offset from the end
var joeBlack = coffee.slice(-2);     // ['water', 'beans']

slice() does not alter the original array. To be fair, you can also clone an array with a loop, concat, and from().

The ES6 Way

let arr1 = [1,2,3];
let arr2 = [4,5,6];

let newArr = [...arr1]; // [1,2,3]
// just like arr.slice() above

let newArr2 = [...arr1, ...arr2]; // [1,2,3,4,5,6]

In my opinion, using the spread operator is a lot easier to read, and understand compared to slice() when copying an entire array. The verb slice means to cut up, and if you use the parameters within slice(x,x) then that reads better, imho.

ES6 Issues

The spread operator ... for copying arrays has some issues. First, if the array is an multidimensional array, it starts to act funny, as well as affecting the arrays.

Additionally, over on stackoverflow there's a great thread on the speed of the different ways to copy an array.