Copy javascript array to new array

I want to create an array from an existing array in order to modify the new array without affecting the old one. I understand that arrays are mutable, and so the new array affects the old one.

eg.

old = ["Apples", "Bananas"]; new = old; new.reverse(); 

The old one was also canceled.

In Python, I can just do new = list(old) , but doing new = new Array(old); puts the old list inside the list.

+47
javascript
Mar 30 '13 at 19:15
source share
2 answers

You can use the .slice method:

 var old = ["Apples", "Bananas"]; var newArr = old.slice(0); newArr.reverse(); // now newArr is ["Bananas", "Apples"] and old is ["Apples", "Bananas"] 

Array.prototype.slice returns a shallow copy of part of the array. Providing 0 as the first parameter means that you are returning a copy of all elements (starting at index 0)

+102
Mar 30 '13 at 19:16
source share

Try to execute

 newArray = oldArray.slice(0); 
+9
Mar 30 '13 at 19:16
source share



All Articles