
There are times we need to copy arrays quickly.
Example below, we have array1, we want to quickly create array2 with all array1 original data.
const array1 = ["get", "set", "go"];
const array2 = array1;
console.log(array1, array2);
RESULT
// array1 = [ get, set, go]
// array2 = [ get, get, go]
What happens when we change array2 ?
array2 = ["changed", "get", "go"];
console.log(array1, array2);
RESULT
// array1 values = changed, set, go
// array2 values = changed, set, go
Data in array1 changed as well. We never made changes or modified array2 in anyway. This behaviour is expected in Javascript, without proper referencing between 2 arrays. Changing one array will directly change another array it is referenced to
This is because using = operator mean we will not only copy the original array but also reference as well.
So how do we properly copy an array. Fortunately there are 4 methods at our disposal. Lets use our original arrays to demonstrate
1. Slice method
const array3 = array1.slice();
array3.push("pushed");
console.log(array3);
// array3 = ["changed", "set", "go", "pushed"]
console.log(array1);
// array1 = ["changed", "set", "go"]
2. Use Concat
const array4 = [].concat(array1);
3. Use spread ES6 methods, the limitation of this method is it only goes one level deep when copying an array. For multi-layered array this method will not be useful as we can see in the example below.
const data = [[1, 2], [3], [5, 6]];
const cloneOfDatas = [...data];
cloneOfDatas[0][0] = "modified";
console.log(cloneOfDatas);
// [["modified", 2], [3], [5, 6]]
console.log(data);
// [["modified", 2], [3], [5, 6]]
4. Use Array.from
const array6 = Array.from(array1);
All methods above allow us to quickly copy the original array and modify new arrays without changing the state of the original array.