Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

I want to form an array from an existing array so I can modify the new array without affecting the old. I realise arrays are mutable and this is why the new array affects the old.

E.g.

old = ["Apples", "Bananas"];
new = old;

new.reverse();

Old has also been reversed.

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

share|improve this question

marked as duplicate by Felix Kling, lifetimes, jwueller, halex, Lion Mar 30 '13 at 19:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
In ES6 you can use spread syntax example: var arrOld = ["Apples", "Bananas"]; var arrNew= [...arrOld]; – GibboK Aug 11 at 20:36
up vote 78 down vote accepted

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 a portion of an array. Giving it 0 as the first parameter means you are returning a copy of all the elements (starting at index 0 that is)

share|improve this answer
    
thanks! i'll set to answered when I can. – jdborg Mar 30 '13 at 19:20
    
No problem, glad it helped. – Benjamin Gruenbaum Mar 30 '13 at 19:33
4  
You can just use old.slice() since 0 is the default. See slice() docs – Jon Onstott Jun 4 '15 at 18:22
    
@Kris - In that fiddle you used sPlice, not slice. – dmon Apr 6 at 18:43

Try the following

newArray = oldArray.slice(0);
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.