Sub topic 2
Iterating Sets and Removing Duplicates
This chapter assumes you know how to create Maps and Sets, how for...of and spread work, and how primitives differ from object references.
Iterating Sets and Removing Duplicates
A Set iterates its values in insertion order. values() and keys() return the same thing. entries() yields [value, value] pairs so that a Set has the same iteration API as a Map.
const tags = ['js', 'css', 'js', 'html', 'css'];
const uniqueTags = [...new Set(tags)];
console.log(uniqueTags); // ['js', 'css', 'html']
for (const tag of new Set(tags)) {
console.log(tag); // js, css, html
}Deduplication keeps the first occurrence of each value. Objects are compared by reference, so two look-alike objects both survive.
When to Use a Map Instead of an Object
| Need | Map | Plain object |
|---|---|---|
| Non-string keys | Any value | Strings and symbols only |
| Size | `map.size` | `Object.keys(o).length` |
| Frequent add/delete | Optimized for it | Slower in many engines |
| Inherited key collisions | None | `toString` and similar names come from the prototype |
| JSON support | Manual | Built in |
Use an object for fixed, record-like data. Use a Map for dynamic lookup tables.
Union, Intersection, Difference, and Subset Checks
The ES2025 Set methods return new Sets or booleans. They never change the original Sets.
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a.union(b)]); // [1, 2, 3, 4]
console.log([...a.intersection(b)]); // [2, 3]
console.log([...a.difference(b)]); // [1]
console.log([...a.symmetricDifference(b)]); // [1, 4]
console.log(a.isSubsetOf(new Set([1, 2, 3, 4]))); // true
console.log(a.isDisjointFrom(new Set([7, 8]))); // trueConverting to Arrays, Objects, and JSON
const settings = { theme: 'dark', fontSize: 14 };
const map = new Map(Object.entries(settings));
console.log(Object.fromEntries(map)); // { theme: 'dark', fontSize: 14 }
console.log(JSON.stringify(map)); // '{}'
const json = JSON.stringify([...map]);
const restored = new Map(JSON.parse(json));
console.log(restored.get('theme')); // 'dark'Grouping Data with Map.groupBy
const inventory = [
{ name: 'apple', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'pear', type: 'fruit' }
];
const byType = Map.groupBy(inventory, (item) => item.type);
console.log(byType.get('fruit').map((i) => i.name)); // ['apple', 'pear']The value returned by the callback becomes the group's key, and that key can be any value, including an object.
Reachability and Garbage Collection
The garbage collector frees an object once no chain of references from a root, such as a global or a live local variable, can reach it. A Map or Set holds its entries strongly. An object stored in a Map stays in memory as long as the Map does, even if nothing else uses it. Weak collections exist to remove that limit.
Exercise
What does [...new Set([1, '1', 1, NaN, NaN])] produce, and why?
Show answer
[1, '1', NaN]. SameValueZero treats the number 1 and the string '1' as different values, and it treats NaN as equal to itself.
Exercise
Why does JSON.stringify(new Map([['a', 1]])) return '{}'?
Show answer
A Map has no enumerable own properties, so JSON.stringify sees an empty object. Serialize [...map] instead.