Javascript copy array to new array

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

Try the following

newArray = oldArray.slice(0);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoedborgView Question on Stackoverflow
Solution 1 - JavascriptBenjamin GruenbaumView Answer on Stackoverflow
Solution 2 - JavascriptJaredParView Answer on Stackoverflow