When copying an array in JavaScript to another array:
var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']
I realized that arr2
refers to the same array as arr1
, rather than a new, independent array. How can I copy the array to get two independent arrays?
Quick Examples:
Important!
Most of answers here works for particular cases.
If you don't care about deep/nested objects and props use (ES6):
let clonedArray = [...array]
but if you want to do deep clone use this instead:
let cloneArray = JSON.parse(JSON.stringify(array))
For lodash users:
let clonedArray = _.clone(array)
documentationand
let clonedArray = _.cloneDeep(array)
documentationThere's the newly introduced
Array.from
, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:Reference: Here
Or
Array.prototype.map
may be used with an identity function:Reference: Here
Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.
Add the following code in your JavaScript file:
And simply use
It will work.
I personally think Array.from is a more readable solution. By the way, just beware of its browser support.
You could use ES6 with spread Opeartor, its simpler.
There are limitations..check docs Spread syntax @ mozilla