Create a new array without affecting the values from the old array
I am trying to create a copy of an existing array and remove some elements from the copy of the array without affecting the original. I've tried this:
var new_arr = old_arr; //when I remove from new array the items from old array are also removed
How do I create a completely new copy of an existing array?
Update:
When I do this:
var new_arr = old_arr.slice();
and then:
new_arr[0].shift();
new_arr[1].shift();
Items from old_array are removed. It is a two dimensional array.
+5
London
source
to share
2 answers
You can use two methods, these are:
function clone (src) {
return JSON.parse(JSON.stringify(src));
}
or that:
var newArray = oldArray.slice();
+11
sourcecode
source
to share
Using Yoshi's answer, you can extend the Array prototype (just a helper):
Array.prototype.clone = function() {
return this.slice(0);
}
+1
Koste
source
to share