DEV Community

Discussion on: How to Deep Clone an Array in JavaScript

Collapse
tailcall profile image
Anton Istomin

One has to be really careful with JSON solution! It doesn't work with values not compatible with JSON. Examples:

function nestedCopy(array) {
    return JSON.parse(JSON.stringify(array));
}

// undefineds are converted to nulls

nestedCopy([1, undefined, 2]) // -> [1, null, 2]

// DOM nodes are converted to empty objects

nestedCopy([document.body, document.querySelector('p')]) // -> [{}, {}]

// JS dates are converted to strings

nestedCopy([new Date()]) // -> ["2019-03-04T10:09:00.419Z"]

Consider using a library function if you have to work with such data.

Collapse
vipinkumarsn4 profile image
Vipin Saini

Wow.
This is really cool!
You have added a gem to the post!
Thanks!

Collapse
samanthaming profile image
Samantha Ming Author

Yes! Very good point, let me add that to the code notes! Thanks for noting that 👏