56

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.

1
  • In ES6 you can use spread syntax example: var arrOld = ["Apples", "Bananas"]; var arrNew= [...arrOld]; Commented Aug 11, 2016 at 20:36

2 Answers 2

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)

4
  • 14
    You can just use old.slice() since 0 is the default. See slice() docs Commented Jun 4, 2015 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. Commented Jun 17, 2017 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 Commented Jun 21, 2018 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. Commented Jun 21, 2018 at 13:26
9

Try the following

newArray = oldArray.slice(0);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.