55

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.

joedborg
  • 17,651
  • 32
  • 84
  • 118
  • In ES6 you can use spread syntax example: `var arrOld = ["Apples", "Bananas"]; var arrNew= [...arrOld];` – GibboK Aug 11 '16 at 20:36

2 Answers2

111

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)

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 14
    You can just use `old.slice()` since 0 is the default. See [slice() docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) – Jon Onstott Jun 04 '15 at 18:22
  • This is a great semi hack. I say hack because its not really clear what is going while reading the code without knowledge of how slice behaves. Firefox has an `array.values()` method which copies the values like this. Unfortunately, no other browsers support the method. – mattdevio Jun 17 '17 at 21:47
  • That hack won't work on multi dimensional arrays. if you have `var oldArr = [ [1,2], [3,4] ]` and did `var newArr = oldArr.slice(0)` and then change `newArr` with `newArr[1][0] = 5` and check `oldArr[0][0]` you will notice it will be updated too. So the only way to copy and to loop through and slice each value – Joseph Jun 21 '18 at 10:00
  • @Joseph this is not a hack - it shallow clones - if you want a deep clone (JS has no concept of multidimensional arrays - just arrays of arrays) - you can `JSON.parse(JSON.stringify(old))` though that's rarely a useful thing to do. – Benjamin Gruenbaum Jun 21 '18 at 13:26
9

Try the following

newArray = oldArray.slice(0);
Seth
  • 10,198
  • 10
  • 45
  • 68
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454