Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript copy array to new array [duplicate]

Tags:

javascript

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.

like image 827
joedborg Avatar asked Mar 30 '13 19:03

joedborg


People also ask

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

How do you make a shallow copy of an array?

Array Clone – Shallow Copy In Java, to create clone of array, you should use clone() method of array. It creates a shallow copy of array. Cloning always creates shallow copy of array. Any change (in original array) will be reflected in cloned array as well.


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 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)

like image 194
Benjamin Gruenbaum Avatar answered Sep 21 '22 11:09

Benjamin Gruenbaum


Try the following

newArray = oldArray.slice(0); 
like image 39
JaredPar Avatar answered Sep 22 '22 11:09

JaredPar