Set Methods
Set Methods
Section titled “Set Methods”Introduction
Section titled “Introduction”Set provides a simple API for adding, checking, and removing unique values.
Basic Operations
Section titled “Basic Operations”const set = new Set();
// Add — only adds if value doesn't existset.add(1);set.add(2);set.add(2); // ignored — already existsset.add(3);console.log(set); // Set(3) { 1, 2, 3 }
// Has — check if value existsconsole.log(set.has(1)); // trueconsole.log(set.has(4)); // false
// Size — number of unique valuesconsole.log(set.size); // 3
// Delete — remove a specific valueset.delete(2);console.log(set.has(2)); // falseconsole.log(set.size); // 2
// Clear — remove all valuesset.clear();console.log(set.size); // 0Initializing with Values
Section titled “Initializing with Values”// From arrayconst set = new Set([1, 2, 3, 2, 1]);console.log([...set]); // [1, 2, 3]
// From stringconst chars = new Set('hello');console.log([...chars]); // ['h', 'e', 'l', 'o']Deduplication
Section titled “Deduplication”// Remove duplicates from arrayconst numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5];const unique = [...new Set(numbers)];console.log(unique); // [1, 2, 3, 4, 5]
// Check if array has duplicatesfunction hasDuplicates(arr) { return new Set(arr).size !== arr.length;}console.log(hasDuplicates([1, 2, 3])); // falseconsole.log(hasDuplicates([1, 2, 2])); // trueIteration
Section titled “Iteration”const set = new Set(['a', 'b', 'c']);
for (const value of set) console.log(value);
// forEachset.forEach(value => console.log(value));
// Convert to arrayconst arr = [...set]; // ['a', 'b', 'c']const arr2 = Array.from(set); // ['a', 'b', 'c']Objects in Set
Section titled “Objects in Set”const set = new Set();const obj1 = { id: 1 };const obj2 = { id: 2 };const obj3 = { id: 1 }; // different reference — treated as unique!
set.add(obj1);set.add(obj2);set.add(obj3); // added because obj3 ≠ obj1
console.log(set.size); // 3console.log(set.has(obj1)); // trueconsole.log(set.has({ id: 1 })); // false — different referenceSummary
Section titled “Summary”add()adds if value doesn’t existhas()is O(1) for lookupsdelete()removes a valuesizeshows unique value count- Great for deduplication and membership checks