Horje
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 }



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What is Map Coercion in JavaScript ? What is Map Coercion in JavaScript ?
Can a Map use Functions as Keys? Can a Map use Functions as Keys?
What is Destructuring in ES6 ? What is Destructuring in ES6 ?
What is the DOM (Document Object Model) ? What is the DOM (Document Object Model) ?
What is LocalStorage & SessionStorage Objects in JavaScript ? What is LocalStorage & SessionStorage Objects in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12