🔸 Part 1: Set
- The Unique Value Hero
What is a Set
?
- A
Set
is a collection of unique values (no duplicates). - Maintains the insertion order.
- Values can be any type: strings, numbers, objects, etc.
Basic Example
🔥 Advanced Use Cases for Set
1.1. Remove duplicates from an array
1.2. Check for duplicates
1.3. Use Set for managing tags (case-insensitive)
🔸 Part 2: Map
- The Key-Value Power Tool
What is a Map
?
- A
Map
holds key-value pairs, just like anObject
. - Keys can be any type, even objects or functions.
- Maintains the insertion order.
- Built-in methods:
set()
,get()
,has()
,delete()
, etc.
Basic Example
🔥 Advanced Use Cases for Map
2.1. Use objects as keys
2.2. Count item occurrences
2.3. Implement caching with Map
Combine Map
+ Set
: Real-Life Grouping
Group users by role, with unique names
Map vs Set - Quick Reference
Feature | Map | Set |
---|---|---|
Structure | Key => Value | Value only (no key) |
Key type | Any (even objects) | N/A |
Duplicates allowed | Keys unique, values can repeat | No duplicates allowed |
Order | Maintains insertion order | Maintains insertion order |
Use Case | Storing related data (key-value) | Ensuring unique values |
Pro Tips Recap 💡
Scenario | Use Set | Use Map |
---|---|---|
Remove duplicates from array | ✅ | ❌ |
Count frequency of items | ❌ | ✅ |
Manage toggle states | ✅ | ✅ |
Cache previously fetched data | ❌ | ✅ |
Store tags / labels | ✅ | ❌ |
Store structured key-value | ❌ | ✅ |
Last updated: April 14, 2025