Set
The Set object is a collection of unique values. Unlike arrays, each value can occur only once in a Set. Sets are useful for eliminating duplicates and for membership testing.
What Problem Does Set Solve?
Section titled “What Problem Does Set Solve?”Arrays have limitations for certain use cases:
- No built-in uniqueness enforcement
- Checking existence requires iteration (O(n))
- Removing duplicates is verbose
Key Characteristics
Section titled “Key Characteristics”| Feature | Description |
|---|---|
| Uniqueness | Each value appears only once |
| Any values | Can store primitives and objects |
| Order | Maintains insertion order |
| Size | .size property for length check |
| Performance | O(1) lookup time with has() |
Syntax
Section titled “Syntax”const set = new Set();const setFromIterable = new Set([1, 2, 3, 3, 4]); // Creates Set {1,2,3,4}Key Points
Section titled “Key Points”- Sets automatically remove duplicate values.
- Values are compared using SameValueZero algorithm.
- Insertion order is preserved.
NaNcan be stored (only one NaN).- Sets are iterable by default.
Example Code
Section titled “Example Code”// Creating Setsconst emptySet = new Set();console.log(emptySet.size); // 0
// From array (duplicates removed)const numberSet = new Set([1, 2, 3, 3, 4, 4, 5]);console.log(numberSet); // Set {1, 2, 3, 4, 5}console.log(numberSet.size); // 5
// From stringconst charSet = new Set("hello");console.log(charSet); // Set {'h', 'e', 'l', 'o'} (l appears only once)
// Mixed types (primitives)const mixedSet = new Set([1, "1", true, "true"]);console.log(mixedSet.size); // 4 (1 and '1' are different)
// Objects are unique by referenceconst obj1 = { id: 1 };const obj2 = { id: 1 };const objSet = new Set([obj1, obj2, obj1]);console.log(objSet.size); // 2 (obj1 and obj2 are different objects)
// NaN handling (only one NaN)const nanSet = new Set([NaN, NaN, NaN]);console.log(nanSet.size); // 1