5

How to Clone a Set in JavaScript ?

 7 months ago
source link: https://www.geeksforgeeks.org/how-to-clone-a-set-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Clone a Set in JavaScript ?

Courses

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 }

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Three 90 Challenge ending on 5th Feb! Last chance to get 90% refund by completing 90% course in 90 days. Explore offer now.
Last Updated : 02 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK