Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  189] [ 4]  / answers: 1 / hits: 87929  / 11 Years ago, sat, march 30, 2013, 12:00:00

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.


More From » javascript

 Answers
21

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)


[#79223] Friday, March 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;