Borislav Hadzhiev
Thu Oct 28 2021·2 min read
Photo by Duncan Shaffer
To create a deep copy of a Set
:
Set
to an array.JSON.stringify()
method to stringify the array.JSON.parse()
method to parse the string back into an array.Set()
constructor.const existingSet = new Set([[1, 2, 3]]); const deepCopy = new Set(JSON.parse( JSON.stringify(Array.from(existingSet)) )); console.log(deepCopy); // 👉️ {[1, 2, 3]}
We used the
Array.from
method to convert the Set
into a two dimensional array.
const existingSet = new Set([[1, 2, 3]]); // 👇️ [ [1, 2, 3] ] console.log(Array.from(existingSet));
The next step is to use the JSON.stringify method to convert the array to a JSON string.
Then, we used the JSON.parse method to parse the string back into an array.
The last step is to pass the two dimensional array to the Set() constructor.
JSON.stringify
method, so that all nested objects lose their reference.If we then try to mutate the array in the new Set
, it wouldn't affect the
existing Set
.
const existingSet = new Set([[1, 2, 3]]); const deepCopy = new Set(JSON.parse( JSON.stringify(Array.from(existingSet)) )); // 👇️ Mutate the nested array for (const item of deepCopy) { item.pop(); } console.log(deepCopy); // 👉️ {[1, 2]} console.log(existingSet); // 👉️ {[1, 2, 3]}
We used the pop
method to mutate the array in the deep copied Set
. However,
notice that the array in the existing Set
wasn't affected.
The nested arrays in the Sets
have a different reference and location in
memory because we used the JSON.stringify
method.