How to copy an array in Javascript
In this tutorial, we are going to see how to copy an array in Javascript. There are two types of copies that can be made on an array.
- Simple copy
- Deep copy
Simple copy
Arrays in javascript are just objects with properties and methods. When we directly assign an array to another variable, it is copied superficially.
This means that it only references the array, it does not copy all the elements.
[st_adsense]
Example:
var arr1 = [1, 2, 3, 4]; //simple copy var arr2 = arr1; console.log(arr2); //[1, 2, 3, 4]; //Update the original array arr1.push(5); //[1, 2, 3, 4, 5] //The update is reflected in the copied array console.log(arr2); //[1, 2, 3, 4, 5]
Deep copy
We can concatenate the original array with an empty array and return it to create a deep copy.
var arr1 = [1, 2, 3, 4]; //Deep copy var arr2 = [].concat(tab1); console.log(arr2); //[1, 2, 3, 4]; //Update the original array arr1.push(5); //[1, 2, 3, 4, 5] //The update is not reflected in the copied array console.log(arr2); //[1, 2, 3, 4][st_adsense]