In JavaScript, a Set is a collection of unique values. Unlike arrays, sets do not allow duplicate elements, which makes them useful when you need to store distinct values.
You can create a Set using the Set
constructor. Here is an example:
// Creating a Set with values let numbers = new Set([1, 2, 3, 4, 5]); // Display the Set console.log(numbers); // Set { 1, 2, 3, 4, 5 }
Here are some important properties and methods of a Set:
// Methods and properties in action let fruits = new Set(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.add("Apple"); // Duplicate, will be ignored console.log(fruits.size); // 3 console.log(fruits.has("Banana")); // true console.log(fruits.has("Mango")); // false fruits.delete("Banana"); console.log(fruits); // Set { "Apple", "Cherry" } fruits.clear(); console.log(fruits); // Set {}
Sets can be used for more advanced operations like finding the union or intersection of two sets. Here's a brief example:
// Union of two sets let setA = new Set([1, 2, 3]); let setB = new Set([3, 4, 5]); let union = new Set([...setA, ...setB]); console.log(union); // Set { 1, 2, 3, 4, 5 } // Intersection of two sets let intersection = new Set([...setA].filter(x => setB.has(x))); console.log(intersection); // Set { 3 }
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!