copying an array of objects in javascript

+2 votes
asked Dec 13, 2012 in java script by jonathan (3,105 points)


How to copy an array of objects to another array in Javascript?

var qwerty1 = arr;
var qwerty2 = arr;

Both qwerty1 and qwerty2 may look different but point to the same reference. I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.

Any light in this regard?

1 Answer

0 votes
answered Dec 13, 2012 by arthi (1,110 points)

The idiomatic way to copy an array in Javascript is to use concat:

var qwerty1 = arr.concat();
var qwerty2 = arr.concat();