Copy array by value
Asked Answered
C

40

2136

When copying an array in JavaScript to another array:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  // Now, arr1 = ['a','b','c','d']

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

Cornwall answered 20/9, 2011 at 13:38 Comment(8)
It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfoLamia
jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an arrayDeb
jsperf.com/flat-array-copyGryphon
For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. [] or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.Chanson
It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Incandescence
All yo need to do is ; var arr2 = new Array(arr2). Check out my answer below. linkPolaris
Well when you state a = b; you actually tell the program to point in both cases to a same symbolic link in random access memory. And when a value at this symbolic link is changed it affects a and b... So if you use a spread operator a= [...b]; program will create an additional symbolic link to a different location in random access memory and you can then manipulate a and b independently.Inveterate
let oldArray = [1, 2, 3, 4, 5]; let newArray = oldArray.slice(); console.log({newArray});Breadnut
E
3133

Use this:

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

Basically, the slice() operation clones the array and returns a reference to a new array.

Also note that:

For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

Enisle answered 20/9, 2011 at 13:41 Comment(15)
Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.Cyna
Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.Johnsten
@GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArrayMagistracy
@GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.Magistracy
@Magistracy Generally you are right. In this case my whole JS experience suggests using this lib in almost every project. Lodash for arrays or objects, like Moment for dates, like Express for NodeJS server, like Angular or React for frontend.Margaritamargarite
"Copying array by value in JavaScript" . The SO asked how to copy by value and you said that slice() copies the references of the objects. True that this is a new array. But i think the question was about the objectsPurpleness
So Basically, the slice() operation clones the array and returns the reference to the new array - basically this is a deep copy thenHousehold
Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.Cupulate
@Growler definitely not a deep copy! It will keep all references to original objects.Iormina
slice is bit old, we got a new way in ES6. Checkout samanthaming.com/tidbits/35-es6-way-to-clone-an-arrayPlacket
This is not the exact answer for the question. This method also passes array by reference. But the question is to pass by reference. I will suggest to use <code> var newArray = JSON.parse(JSON.stringify(orgArray));</code> to pass by valueLeucopenia
This is not the exact answer for the question. This method also passes array by reference. But the question is to pass by reference. I will suggest to use var newArray = JSON.parse(JSON.stringify(orgArray)); to pass by valueLeucopenia
The question explicitly states "copy array BY VALUE", not by reference. Yet this answer states "slice() copies object references into the new array". Why this has 3000 upvotes is beyond me. @AbdulhakimZeinu 's comment should be the actual answer to this question.Hunkydory
If .slice() creates a duplicate array what even is the point of using .slice() / creating an extra array if every time you change the array it will affect the other array??? What could be a benefit of having two lists that are completely in sync vs. just having 1 if they're the same thing?Hunkydory
With this solution, array values ​​that are objects are always copied by reference and not by value. Modifying an object in the copied table will also affect the original table.Extragalactic
C
677

In Javascript, deep-copy techniques depend on the elements in an array. Let's start there.

Three types of elements

Elements can be: literal values, literal structures, or prototypes.

// Literal values (type1)
const booleanLiteral = true;
const numberLiteral = 1;
const stringLiteral = 'true';

// Literal structures (type2)
const arrayLiteral = [];
const objectLiteral = {};

// Prototypes (type3)
const booleanPrototype = new Bool(true);
const numberPrototype = new Number(1);
const stringPrototype = new String('true');
const arrayPrototype = new Array();
const objectPrototype = new Object(); // or `new function () {}

From these elements we can create three types of arrays.

// 1) Array of literal-values (boolean, number, string) 
const type1 = [ true, 1, "true" ];

// 2) Array of literal-structures (array, object)
const type2 = [ [], {} ];

// 3) Array of prototype-objects (function)
const type3 = [ function () {}, function () {} ];

Deep copy techniques depend on the three array types

Based on the types of elements in the array, we can use various techniques to deep copy.

Deep copy techniques

Javascript deep copy techniques by element types

Benchmarks

https://www.measurethat.net/Benchmarks/Show/17502/0/deep-copy-comparison

  • Array of literal-values (type1)
    The [ ...myArray ], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where slice() has the highest performance in Chrome, and spread ... has the highest performance in Firefox.

  • Array of literal-values (type1) and literal-structures (type2)
    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.

  • All arrays (type1, type2, type3)

    • structuredClone();
    • The Lo-dash cloneDeep(myArray) or jQuery extend(true, [], myArray) techniques can be used to deep-copy all array-types. Where the Lodash cloneDeep() technique has the highest performance.
    • And for those who avoid third-party libraries, the custom function below will deep-copy all array-types, with lower performance than cloneDeep() and higher performance than extend(true).
function copy(aObject) {
  // Prevent undefined objects
  // if (!aObject) return aObject;

  let bObject = Array.isArray(aObject) ? [] : {};

  let value;
  for (const key in aObject) {

    // Prevent self-references to parent object
    // if (Object.is(aObject[key], aObject)) continue;
    
    value = aObject[key];

    bObject[key] = (typeof value === "object") ? copy(value) : value;
  }

  return bObject;
}

So to answer the question...

Question

var arr1 = ['a','b','c'];
var arr2 = arr1;

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

Answer

Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where slice() and spread ... have the highest performance.

arr2 = arr1.slice();
arr2 = [...arr1];
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = structuredClone(arr1);
arr2 = copy(arr1); // Custom function needed, and provided above
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = jQuery.extend(true, [], arr1); // jQuery.js needed
Chanson answered 8/5, 2014 at 8:36 Comment(13)
Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).Siddon
Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.Chanson
Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagneSkipp
splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.Chanson
Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.Darnel
That custom deep-copy recursive function is splendid! Thanks for sharing and for that extremely extensive answer! I had a hard time getting .slice() to work, since I was modifying an object through the reference... after the deep copy - works like a charm.Iormina
Note that in most cases deep copying can be simplified if you know the structure of your array. If you have an array of objects, just do arr.map(it => ({ ...it })), if you have an array of arrays: arr.map(Array.from)Dario
@JonasWilms - Just to be clear to the reader, and paraphrasing. "If you have an array of objects (which are not nested), just do arr.map(it => ({ ...it })), if you have an array of arrays (without elements that are objects): arr.map(Array.from)."Chanson
Yes, I think its worth mentioning ... Maybe that should be part of tue answer?Dario
@JonasWilms - That is apart of the answer. It's covered under the custom function, which uses the for-in loop (as it has higher performance than .map) to deep copy elements into a new arrayChanson
No it is not. A custom clone function will always be faster than one for the general case.Dario
@JonasWilms - Regardless of performance, I don't want to add your expressions to the answer because they don't offer a new solution. They simply loop over elements in an array and make a flat copy, and that's already being done by the custom function.Chanson
IMO these all have bad legibility. The fact that someone is meaning to clone an array is not apparent to me. What is wrong with calling it x.clone()?Athamas
R
219

You can use array spreads ... to copy arrays.

const itemsCopy = [...items];

Also if want to create a new array with the existing one being part of it:

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];

Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.

More info on spreads

Raoul answered 3/7, 2015 at 14:46 Comment(2)
This won't work for deep copy. Deep Clone an Array in JavaScript.Purse
Beware that this will also create new entries for "undefined" in the original array. Which might brake your code.Teide
A
166

No jQuery needed... Working Example

var arr2 = arr1.slice()

This copys the array from the starting position 0 through the end of the array.

It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...

If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.

Acuity answered 20/9, 2011 at 13:39 Comment(6)
No this would not be a deep copy.Acuity
Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);Squish
What's the difference between this answer and the accepted answer?Rosecan
getting error in console for your given example "TypeError: window.addEvent is not a function"Whiff
@IsaacPak This was answered 2 mins before that.Giffer
var arr2 = arr1.slice(0); This way just work for simple Arrays. If u have Complex Array like array of Objects then you must use another way like: const arr2 = JSON.parse(JSON.stringify(arr1));Defeatist
A
87

This is how I've done it after trying many approaches:

var newArray = JSON.parse(JSON.stringify(orgArray));

This will create a new deep copy not related to the first one (not a shallow copy).

Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)

Adnate answered 23/4, 2014 at 13:32 Comment(7)
This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loopsMozellamozelle
Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.Eparchy
This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.Siddon
Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?Starch
This does a deep copy. The question didn't ask for that. Although it is useful, it does something different than the other answers.Darnel
Slice or splice will not work when you have array of arrays. However, this will work well. Yes as per @LawrenceDol, it is inefficient as compared to other available methods. Use this only if you have array of arrays.Forthright
Yes, works the best as it just lost all information about the source array. I still had troubles with the spread operator, because if an array contains arrays, the arrays are still copied as referencing arrays.Bulge
B
77

An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:

var array2 = [].concat(array1);

The second method is:

var array2 = array1.concat();

Cohen (in the comments) pointed out that this latter method has better performance.

The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.

Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:

var array2 = [].concat(array1 || []);

Or, for the second method:

var array2 = (array1 || []).concat();

Note that you can also do this with slice: var array2 = (array1 || []).slice();.

Bugbear answered 18/10, 2012 at 0:11 Comment(2)
Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5Cyna
Its worth noting that if array1 isn't an array then [].concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = [].concat(array1 || []);Schear
K
30

Important!

Most of answers here works for particular cases.

If you don't care about deep/nested objects and props use (ES6):

let clonedArray = [...array]

but if you want to do deep clone use this instead:

let cloneArray = JSON.parse(JSON.stringify(array))*

*functions won't be preserved (serialized) while using stringify, you will get result without them.


For lodash users:

let clonedArray = _.clone(array) documentation

and

let clonedArray = _.cloneDeep(array) documentation

Kipp answered 22/8, 2018 at 14:46 Comment(0)
B
24

I personally think Array.from is a more readable solution. By the way, just beware of its browser support.

// clone
let x = [1, 2, 3];
let y = Array.from(x);
console.log({y});

// deep clone
let clone = arr => Array.from(arr, item => Array.isArray(item) ? clone(item) : item);
x = [1, [], [[]]];
y = clone(x);
console.log({y});
Bova answered 9/3, 2016 at 12:1 Comment(1)
Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.Fanaticize
C
22

Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.

Add the following code in your JavaScript file:

Object.prototype.clone = function() {
    var newObj = (this instanceof Array) ? [] : {};
    for (i in this) {
        if (i == 'clone') 
            continue;
        if (this[i] && typeof this[i] == "object") {
            newObj[i] = this[i].clone();
        } 
        else 
            newObj[i] = this[i]
    } return newObj;
};

And simply use

var arr1 = ['val_1','val_2','val_3'];
var arr2 = arr1.clone()

It will work.

Constant answered 12/12, 2012 at 16:22 Comment(7)
i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'Yeoman
My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')Yeoman
.slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525gPlankton
@Plankton but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1Lasagne
Excellent code. One question I have, I actually tried to copy one array into another like this var arr1 = new Array() and then var arr2 = arr1; If I change something in arr2 the change happens also to arr1. However, if I use the clone prototype you made, It actually creates a complete new instance of that array or in other words it copies it. So is this a browser problem? or javascript by default sets the two variables by one pointing to an other with the use of pointers when someone does var arr2=arr1 and why does not happen with integer variables? see jsfiddle.net/themhz/HbhtASmithery
@themis integers and strings are basic variable types and can be natively passed by value. Anything else can't.Ervinervine
This is the only one working with global vars, splice and concat dont work on a global var.Slot
P
22

From ES2015,

var arr2 = [...arr1];
Poltroon answered 24/12, 2015 at 7:14 Comment(0)
L
12

If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:

var arr1 = ['a','b','c'];
var arr2 = [...arr1]; //copy arr1
arr2.push('d');

console.log(arr1)
console.log(arr2)
<script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>
Loney answered 3/7, 2015 at 9:31 Comment(0)
A
12

Primitive values are always pass by its value (copied). Compound values however are passed by reference.

So how do we copy this arr?

let arr = [1,2,3,4,5];

Copy an Array in ES6

let arrCopy = [...arr]; 

Copy n Array in ES5

let arrCopy = arr.slice(); 
let arrCopy = [].concat(arr);

Why `let arrCopy = arr` is not passing by value?

Passing one varible to another on Compound values such as Object/Array behave difrently. Using asign operator on copand values we pass reference to an object. This is why the value of both arrays are changing when removing/adding arr elements.

Exceptions:

arrCopy[1] = 'adding new value this way will unreference';

When you assign a new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array.

read more

Advancement answered 31/12, 2018 at 1:28 Comment(0)
J
9

Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references. What you can do is to loop and slice() each sub-array individually

var arr = [[1,1,1],[2,2,2],[3,3,3]];
var arr2 = arr.slice();

arr2[0][1] = 55;
console.log(arr2[0][1]);
console.log(arr[0][1]);

function arrCpy(arrSrc, arrDis){
 for(elm in arrSrc){
  arrDis.push(arrSrc[elm].slice());
}
}

var arr3=[];
arrCpy(arr,arr3);

arr3[1][1] = 77;

console.log(arr3[1][1]);
console.log(arr[1][1]);

same things goes to array of objects, they will be copied by reference, you have to copy them manually

Jewel answered 15/4, 2014 at 13:40 Comment(1)
This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!Medeah
F
8
let a = [1,2,3];

Now you can do any one of the following to make a copy of an array.

let b = Array.from(a); 

OR

let b = [...a];

OR

let b = new Array(...a); 

OR

let b = a.slice(); 

OR

let b = a.map(e => e);

Now, if i change a,

a.push(5); 

Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.

But i think, in all the methods above Array.from is better and made mainly to copy an array.

Freighter answered 18/11, 2018 at 6:43 Comment(1)
which one is the fastest?Duodecillion
D
8

I would personally prefer this way:

JSON.parse(JSON.stringify( originalObject ));
Demonic answered 25/3, 2019 at 11:53 Comment(1)
So the way suggested here?Skeptical
F
8

I found this method comparatively easier:

let arr = [1,2,3,4,5];
let newArr = [...arr];
console.log(newArr);
Florio answered 6/9, 2022 at 12:17 Comment(1)
Has already been answered here (and a bunch of other answers).Algebraist
E
7

You must use best practice for this question when there are a lot of answers.

I recommend to you use array spreads … to copy arrays.

var arr1 = ['a','b','c'];

var arr2 = […arr1];

Earthward answered 15/11, 2021 at 5:48 Comment(0)
A
6

As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?

Here are few ways to do it:

Imagine we have this array in your code:

var arr = [1, 2, 3, 4, 5];

1) Looping through the array in a function and return a new array, like this:

 function newArr(arr) {
      var i=0, res = [];
      while(i<arr.length){
       res.push(arr[i]);
        i++;
       }
   return res;
 }

2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:

var arr2 = arr.slice(); // make a copy of the original array

3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:

var arr2 = arr.concat();

4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:

var arr2 = JSON.parse(JSON.stringify(arr));

5) Array.from method, this is not widely supported, before use check the support in different browsers:

const arr2 = Array.from(arr);

6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:

const arr2 = [...arr];
Atheistic answered 26/3, 2017 at 2:35 Comment(0)
P
5

Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.

var arr1 = ['a','b','c'];
var arr2 = [];

var arr2 = new Array(arr1);

arr2.push('d');  // Now, arr2 = [['a','b','c'],'d']

console.log('arr1:');
console.log(arr1);

console.log('arr2:');
console.log(arr2);

// Following did the trick:
var arr3 = [...arr1];
arr3.push('d');  // Now, arr3 = ['a','b','c','d'];

console.log('arr3:');
console.log(arr3);

Now arr1 and arr2 are two different array variables stored in separate stacks. Check this out on jsfiddle.

Polaris answered 18/5, 2018 at 15:5 Comment(2)
This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).Flanna
@Polaris I hope you don't mind that I edited your answer, completing your snippet code here with your code from jsfiddle, changing document.write(arr2) to console.log(arr2) so that nested array structure would show and better illustrate correct comment from @Timothy003. var arr3 = [...arr1] did the trick, though. Run code snippet to see results. (Output from document.write(arr2) was a bit misleading, hence I don't blame you).Yokefellow
S
5

You could use ES6 with spread Opeartor, its simpler.

arr2 = [...arr1];

There are limitations..check docs Spread syntax @ mozilla

Skive answered 27/6, 2018 at 9:6 Comment(0)
D
5

var arr2 = arr1.slice(0);

This way just work for simple Arrays.

If you have Complex Array like array of Objects then you must use another solutions like:

const arr2 = JSON.parse(JSON.stringify(arr1)); 

For example, we have an array of objects that each cell have another array field in its object ... in this situation if we use slice method then the array fields will copy by Ref and that's mean these fields updates will affect on orginal array same element and fields.

Defeatist answered 15/1, 2022 at 14:53 Comment(0)
V
4

In my particular case I needed to ensure the array remained intact so this worked for me:

// Empty array
arr1.length = 0;
// Add items from source array to target array
for (var i = 0; i < arr2.length; i++) {
    arr1.push(arr2[i]);
}
Vaporization answered 13/5, 2014 at 18:20 Comment(1)
+1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.Mackay
P
4

Make copy of multidimensional array/object:

function deepCopy(obj) {
   if (Object.prototype.toString.call(obj) === '[object Array]') {
      var out = [], i = 0, len = obj.length;
      for ( ; i < len; i++ ) {
         out[i] = arguments.callee(obj[i]);
      }
      return out;
   }
   if (typeof obj === 'object') {
      var out = {}, i;
      for ( i in obj ) {
         out[i] = arguments.callee(obj[i]);
      }
      return out;
   }
   return obj;
}

Thanks to James Padolsey for this function.

Source: Here

Pledgee answered 22/7, 2014 at 12:15 Comment(0)
O
4

If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).

new_array = old_array.slice()

or

new_array = old_array.map((elem) => elem)

or

const new_array = new Array(...old_array);

BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY of the old_array.

For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.

var new_array = JSON.parse(JSON.stringify(old_array));

There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.

Osculation answered 26/9, 2018 at 13:52 Comment(1)
Thanks a lot, your answer was the only one who worked for my scenario,Lithiasis
H
3

If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:

var arr1 = ['a','b','c'];
var arr2 = [];

for (var i=0; i < arr1.length; i++) {
   arr2[i] = arr1[i];
}

You can search for more information on Google about immutable primitive values and mutable object references.

Heimdall answered 20/9, 2011 at 13:45 Comment(1)
You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.Seclude
Z
3

When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:

const oldArr = [1,2,3];

const newArr = oldArr;  // now oldArr points to the same place in memory 

console.log(oldArr === newArr);  // Points to the same place in memory thus is true

const copy = [1,2,3];

console.log(copy === newArr);  // Doesn't point to the same place in memory and thus is false

Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.

Ways of copying an array:

const oldArr = [1,2,3];

// Uses the spread operator to spread out old values into the new array literal
const newArr1 = [...oldArr];

// Slice with no arguments returns the newly copied Array
const newArr2 = oldArr.slice();

// Map applies the callback to every element in the array and returns a new array
const newArr3 = oldArr.map((el) => el);

// Concat is used to merge arrays and returns a new array. Concat with no args copies an array
const newArr4 = oldArr.concat();

// Object.assign can be used to transfer all the properties into a new array literal
const newArr5 = Object.assign([], oldArr);

// Creating via the Array constructor using the new keyword
const newArr6 = new Array(...oldArr);

// For loop
function clone(base) {
	const newArray = [];
    for(let i= 0; i < base.length; i++) {
	    newArray[i] = base[i];
	}
	return newArray;
}

const newArr7 = clone(oldArr);

console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);

Be careful when arrays or objects are nested!:

When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:

let arr1 = [1,2,[1,2,3]]

let arr2 = [...arr1];

arr2[2][0] = 5;  // we change arr2

console.log(arr1);  // arr1 is also changed because the array inside arr1 was copied by reference

So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.

If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:

let arr1 = [1,2,[1,2,3]]

let arr2 = JSON.parse(JSON.stringify(arr1)) ;

arr2[2][0] = 5;

console.log(arr1);  // now I'm not modified because I'm a deep clone

Performance of copying:

So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).

After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.

Source performance test

Zenobiazeolite answered 6/8, 2018 at 10:6 Comment(0)
L
3

structuredClone

The modern way to copy array by value in JavaScript is to use structuredClone:

var arr1 = ['a', 'b', 'c'];
var arr2 = structuredClone(arr1); //copy arr1
arr2.push('d');

console.log(arr1); //a,b,c
console.log(arr2); //a,b,c,d
Lannylanolin answered 9/6, 2023 at 20:0 Comment(0)
E
2

Using jQuery deep copy could be made as following:

var arr2 = $.extend(true, [], arr1);
Expletive answered 12/1, 2017 at 19:26 Comment(0)
C
2

You can also use ES6 spread operator to copy Array

var arr=[2,3,4,5];
var copyArr=[...arr];
Cahoon answered 30/6, 2017 at 19:16 Comment(0)
D
2

Here are few more way to copy:

const array = [1,2,3,4];

const arrayCopy1 = Object.values(array);
const arrayCopy2 = Object.assign([], array);
const arrayCopy3 = array.map(i => i);
const arrayCopy4 = Array.of(...array );
Diaspora answered 12/4, 2018 at 7:0 Comment(0)
M
2

For ES6 array containing objects

cloneArray(arr) {
    return arr.map(x => ({ ...x }));
}
Meant answered 4/5, 2018 at 19:9 Comment(0)
M
2

Quick Examples:

  1. If elements in the array are primitive types (string, number, etc.)

var arr1 = ['a','b','c'];
// arr1 and arr2 are independent and primitive elements are stored in 
// different places in the memory
var arr2 = arr1.slice(); 
arr2.push('d');
console.log(arr1); // [ 'a', 'b', 'c' ]
console.log(arr2); // [ 'a', 'b', 'c', 'd' ]
  1. If elements in the array are object literals, another array ({}, [])

var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
// arr1 and arr2 are independent and reference's/addresses are stored in different
// places in the memory. But those reference's/addresses points to some common place
// in the memory.
var arr2 = arr1.slice(); 
arr2.pop();      // OK - don't affect arr1 bcos only the address in the arr2 is
                 // deleted not the data pointed by that address
arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area 
                 // pointed by the addresses in both arr1 and arr2
arr2[1][0] = 9;	 // not OK - same above reason

console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]
  1. Solution for 2: Deep Copy by element by element

var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
arr2 = JSON.parse(JSON.stringify(arr1));
arr2.pop();	  // OK - don't affect arr1
arr2[0].x = 'z';  // OK - don't affect arr1
arr2[1][0] = 9;	  // OK - don't affect arr1

console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]
Montes answered 11/9, 2018 at 13:41 Comment(0)
A
1

Here's a variant:

var arr1=['a', 'b', 'c'];
var arr2=eval(arr1.toSource());
arr2.push('d');
console.log('arr1: '+arr1+'\narr2: '+arr2);
/*
 *  arr1: a,b,c
 *  arr2: a,b,c,d
 */
Amero answered 6/10, 2013 at 6:36 Comment(1)
not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.Teeters
D
1

There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:

var arr1 = [1, 2, 3];
console.log(Array.from(arr1)); // Logs: [1, 2, 3]

Reference: Here

Or Array.prototype.map may be used with an identity function:

function identity(param)
{
    return param;
}

var arr1 = [1, 2, 3],
    clone = arr1.map(identity);

Reference: Here

Dermatophyte answered 10/12, 2014 at 15:45 Comment(2)
+1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .Kreutzer
Be aware Array.from will mutate data, doesn't provide deep copying/deep cloning.Consanguineous
G
1

You can do that in following way :
arr2 = arr1.map(x => Object.assign({}, x));

Globulin answered 31/5, 2018 at 11:50 Comment(0)
Z
1

Here is how you can do it for array of arrays of primitives of variable depth:

// If a is array: 
//    then call cpArr(a) for each e;
//    else return a

const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
let dst = cpArr(src);

https://jsbin.com/xemazog/edit?js,console

Zasuwa answered 13/12, 2018 at 11:10 Comment(0)
R
1

Just writting:

arr2 = arr1.concat();

You are generating new a new array with a copy of the first. Be aware that is a functional way to push an element into the array.

If your code is based on ES6 you can use spread operator as well:

arr2 = [...arr1];
Rolanderolando answered 2/2, 2019 at 15:0 Comment(0)
C
1

structuredClone is a new way of deep cloning.

structuredClone(value)
structuredClone(value, { transfer })

transfer is an array of transferable objects in value that will be moved rather than cloned to the returned object.

You may find it's algorithm quite interesting.

Chromolithography answered 30/12, 2021 at 15:24 Comment(0)
R
0

None of these options worked for me as I was dealing with an array of deeply nested objects. For ES6 I found this solution helpful.

const old_array = [{name:"Nick", stats:{age:25,height:2}},{name:"June", stats:{age:20,height:2}}];

const new_array = old_array.map(e => {
  if (e.name === 'June') {
     e = { ...e };
     e.stats = {...e.stats, age: 22};
   }
  return e;
});

Only the new_array will be affected by this.

Reviel answered 2/10, 2019 at 8:2 Comment(0)
M
-1

After digging on it, I figured out that a clean approach can be:

  const arr1 = [['item 1-1', 'item 1-2'], ['item 2-1', 'item 2-2'], ['item 3-1', 'item 3-2']];

  /**
   * Using Spread operator, it will create a new array with no reference to the first level.
   * 
   * Since, the items are not primitive, they get their own references. It means that any change on them,
   * it will be still reflected on the original object (aka arr1).
   */
  const arr2 = [...arr1];

  /**
   * Using Array.prototype.map() in conjunction Array.prototype.slice() will ensure:
   * - The first level is not a reference to the original array.
   * - In the second level, the items are forced (via slice()) to be created as new ones, so there is not reference to the original items
   */
  const arr3 = arr1.map(item => item.slice());

You need to understand the complexity of the arrays you want to work with to then apply the best solution (aka ➡️ referenced items inside a referenced array)

Metropolis answered 22/4, 2022 at 8:35 Comment(1)
This only works if the elements in the array are all arrays as well.Chandler

© 2022 - 2024 — McMap. All rights reserved.