There are 2 types of array cloning: shallow & deep. Shallow copies only cover the 1st level of the array and the rest are referenced. If you ...
For further actions, you may consider blocking this person and/or reporting abuse
One has to be really careful with JSON solution! It doesn't work with values not compatible with JSON. Examples:
Consider using a library function if you have to work with such data.
Yes! Very good point, let me add that to the code notes! Thanks for noting that 👏
Wow.
This is really cool!
You have added a gem to the post!
Thanks!
Nice summary!
I'd like to add a tiny bit to the nested array example, that when you rest-spread an array, if that array has another nested array as its element, what gets shallow-copied is the reference to the original nested array:
thus creating the mutation effects.
Yup! In those cases, if you want a true copy, you will need to do a deep clone. Thanks for sharing!
As pointed out in other comments, relying on
JSON.parse
andJSON.stringify
to perform a deep cloning is suboptimal (edge cases, performances). Better use the method provided by some library (e.glodash
'scloneDeep
).pulling in an entire library for a single method can also be a kind of suboptimal (versioning, security auditing, vendoring vs. managed dependencies). it's a lot of overhead when there might be a better solution in just not doing deeply nested arrays.
My point is to use an optimised method. Deep cloning arrays or objects may not be very common but if the need arises, I'd recommend using an exisiting solution.
Totally! JSON is the quick&dirty way 😂Lodash is definitely the preferred optimal solution. Thanks for pointing that out 👍
This right here deep copies nested array too
It pushes into a new array with [...matrix[m]]
Hi,
nice post, but i'd like you to note that there are some difference between deepClone and JSON.stringify/parse.
Here an example:
Exactly! Thanks for sharing this! Let me add it to my code notes 👍
In the last clone (recursive code) the function have to return a copy of item, {...item}, in order to create deep cloning, not the item reference.
The whole piece of code is:
const clone = (items) => items.map(item => Array.isArray(item) ? clone(item) : {...item});
Nicely explained. Another quirk of JavaScript I'l know to look out for, but your JSON solution is simple to remember.
I don't think this is javascript specific? And no, it's not a quirk.
Even Java(and most other languages) copies non-primitive data types by reference.
Maybe I misunderstood your comment though.
I'm a primarily a PHP developer so everything about JavaScript is quirky to me. :-)
Let's just pretend I left the obligatory, "But php has a,b,c,d....x,y,z quirks and javascript is so much better" ;)
JSON is your quick and dirty solution. For a more robust solution, I’d go with Lodash 🙂
Just found your ( interesting ) post looking up on how to deep copy an array the right way. While you probably know it by now, the structuredClone() global function now exists since 2022 and is very well supported. It is a good solution to our common headaches !
May this help someone in need, like it did.
Array.form() will do the same operations and same behaviour as [...] spread.
for eg.
let nestedArray = [1, [2], 3];
let arrayCopy = Array.from(nestedArray);
// Make some changes
arrayCopy[0] = '👻'; // change shallow element
console.log(nestedArray); //[1,[2],3]
console.log(arrayCopy); // [ '👻',[2],3]
arrayCopy[1][0] = '💩'; // change nested element
console.log(nestedArray); // [ 1, [ '💩' ], 3 ]
structuredClone API is the more cleaner way to do this now and it is accepted by almost all the browsers now :
array2 = structuredClone(array1);
how would you code the recursion example without using map?
If you want/need to not use ES6 stuff you would simply use a standard for loop.
I didn't test this or anything btw just writing an example off of the top of my head, so no promises lol
I love it! In my current project, I encountered this kind of problem especially in passing by reference of nested arrays. Now, I got it by very friendly explanation. Good job!
It took me a long time to get this reference type. So hopefully I was able to explain it a way that makes sense to you 😄
very helpful, thank you!
You’re welcome! Thanks for reading it 😃
Hi Samantha,
Good Post!
Thanks!
this is the best way to deep copy and you should be cloning html element refs as other people said in the comments that is and easy way to get memory leaks
Amazing post. Simple explanation,simple examples.
Thank you!