How to Clone a Set in JavaScript ?
In JavaScript, you can clone (create a shallow copy of) a Set using the spread operator (...
) or the Set
constructor. Here are two common methods for cloning a Set:
Method 1: Using the Spread Operator
Here, the spread operator is used to create a new Set (clonedSet
) with the elements of the original Set (originalSet
).
let originalSet = new Set([1, 2, 3, 4, 5]);
// Clone the set using the spread operator
let clonedSet = new Set([...originalSet]);
console.log(clonedSet); // Output: Set { 1, 2, 3, 4, 5 }
Method 2: Using the Set Constructor
Here, the Set
constructor is used with the original Set as an argument to create a new Set (clonedSet
). This method works because the Set constructor can accept an iterable object, and a Set is iterable.
let originalSet = new Set([1, 2, 3, 4, 5]);
// Clone the set using the Set constructor
let clonedSet = new Set(originalSet);
console.log(clonedSet); // Output: Set { 1, 2, 3, 4, 5 }