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?
No jQuery needed... Working Example
This copys the array from the starting position
0
through the end of the array.It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...
If you have an array of Reference types, say of type
Object
. The array will be copied, but both of the arrays will contain references to the sameObject
's. So in this case it would seem like the array is copied by reference even though the array is actually copied.An alternative to
slice
isconcat
, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:The second method is:
Cohen (in the comments) pointed out that this latter method has better performance.
The way this works is that the
concat
method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.Lee Penkman, also in the comments, points out that if there's a chance
array1
isundefined
, you can return an empty array as follows:Or, for the second method:
Note that you can also do this with
slice
:var array2 = (array1 || []).slice();
.From ES2015,
If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:
You can search for more information on Google about immutable primitive values and mutable object references.
Use this:
Basically, the
slice()
operation clones the array and returns a reference to a new array. Also note that:For references, strings and numbers (and not the actual object),
slice()
copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.
This is how I've done it after trying many approaches:
This will create a new deep copy not related to the first one (not a shallow copy).
Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)