How to create a Deep Copy of a Set in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

Create a Deep Copy of a Set in JavaScript #

To create a deep copy of a Set:

  1. Convert the Set to an array.
  2. Use the JSON.stringify() method to stringify the array.
  3. Use the JSON.parse() method to parse the string back into an array.
  4. Pass the result to the Set() constructor.
index.js
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.

index.js
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.

Converting the array to a JSON string makes all of the nested arrays or objects lose their reference.

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.

The trick here is to stringify the array, using the 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.

index.js
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee