๐บ๏ธ Collections: Map and Set โ Your Treasure Chests for Data!
Imagine you have two special treasure chests. One chest (called Map) has labeled drawers where each drawer has a name tag AND something inside. The other chest (called Set) is a magic box that only keeps unique treasures โ it automatically throws out any duplicates!
Letโs explore these magical containers!
๐ The Map Object โ Your Labeled Drawer System
What is a Map?
Think of a Map like a drawer organizer with name tags. Each drawer has:
- A label (we call it a โkeyโ) โ like โsocks drawerโ
- Stuff inside (we call it a โvalueโ) โ the actual socks!
Unlike a regular object, a Map can use anything as a label โ even other objects!
// Creating a Map - like getting a new organizer!
const myTreasures = new Map();
// Adding items with labels
myTreasures.set("gold", 100);
myTreasures.set("gems", 50);
myTreasures.set("magic wands", 3);
Why Use Map Instead of Regular Objects?
- Any key type! Objects only allow string keys. Maps allow anything!
- Easy counting! Use
.sizeto count items instantly - Built-in order! Items stay in the order you added them
// Maps can use anything as keys!
const playerScores = new Map();
const player1 = { name: "Alex" };
const player2 = { name: "Sam" };
playerScores.set(player1, 100);
playerScores.set(player2, 85);
๐ ๏ธ Map Methods โ Your Toolbox
Maps come with super helpful tools! Here are the main ones:
.set(key, value) โ Add or Update a Drawer
const snackCounts = new Map();
snackCounts.set("cookies", 5); // Add new
snackCounts.set("cookies", 10); // Update!
.get(key) โ Peek Inside a Drawer
const howManyCookies = snackCounts.get("cookies");
// Returns: 10
.has(key) โ Check if Drawer Exists
snackCounts.has("cookies"); // true
snackCounts.has("carrots"); // false
.delete(key) โ Remove a Drawer
snackCounts.delete("cookies");
// Bye bye cookies drawer!
.clear() โ Empty Everything!
snackCounts.clear();
// All drawers gone!
.size โ Count All Drawers
const petFood = new Map([
["cat", "fish"],
["dog", "bones"],
["rabbit", "carrots"]
]);
console.log(petFood.size); // 3
๐ Map Iteration โ Looking at Everything
Need to see all your treasures? Maps give you three ways to peek!
Loop Through Everything with forโฆof
const fruitColors = new Map([
["apple", "red"],
["banana", "yellow"],
["grape", "purple"]
]);
// Method 1: entries() - key AND value
for (const [fruit, color] of fruitColors) {
console.log(`${fruit} is ${color}`);
}
// Method 2: keys() - just the labels
for (const fruit of fruitColors.keys()) {
console.log(fruit); // apple, banana, grape
}
// Method 3: values() - just the contents
for (const color of fruitColors.values()) {
console.log(color); // red, yellow, purple
}
forEach โ Do Something with Each Item
fruitColors.forEach((color, fruit) => {
console.log(`I love ${color} ${fruit}s!`);
});
โ๏ธ Map vs Object โ Which Should You Choose?
graph TD A["Need to store key-value pairs?"] --> B{What type of keys?} B -->|Only strings| C["Object works fine!"] B -->|Any type| D["Use Map!"] A --> E{Need to count items often?} E -->|Yes| F["Use Map - has .size"] E -->|No| G["Object is okay"] A --> H{Need preserved order?} H -->|Yes| I["Use Map!"] H -->|No| J["Object might work"]
| Feature | Object | Map |
|---|---|---|
| Key types | Strings only | Anything! |
| Size | Manual count | Use .size |
| Order | Not guaranteed | Preserved |
| Iteration | Tricky | Built-in |
| Performance | Good for small | Better for many |
Quick Rule: Use Map when keys arenโt strings or when you need easy iteration!
๐ฏ The Set Object โ Your Magic Duplicate Filter
Now meet Set โ the treasure chest that hates copies! Throw in 10 identical coins, and it keeps only 1.
// Creating a Set
const myPets = new Set();
// Adding items
myPets.add("dog");
myPets.add("cat");
myPets.add("dog"); // Already have a dog!
myPets.add("fish");
console.log(myPets.size); // 3 (not 4!)
Real-World Example
// Track unique visitors
const visitors = new Set();
visitors.add("user123");
visitors.add("user456");
visitors.add("user123"); // Same person!
console.log(visitors.size); // 2 unique visitors!
๐ ๏ธ Set Methods โ Your Uniqueness Toolkit
.add(value) โ Toss In a Treasure
const colors = new Set();
colors.add("blue");
colors.add("red");
colors.add("blue"); // Ignored - already have it!
.has(value) โ Check If Itโs Inside
colors.has("blue"); // true
colors.has("pink"); // false
.delete(value) โ Remove One Item
colors.delete("red");
// Red is gone!
.clear() โ Empty the Whole Chest
colors.clear();
// All colors gone!
.size โ Count Unique Items
const numbers = new Set([1, 2, 2, 3, 3, 3]);
console.log(numbers.size); // 3 (only unique!)
๐ Set Iteration โ Viewing Your Unique Collection
Sets are iterable just like Maps!
const fruits = new Set(["apple", "banana", "cherry"]);
// for...of loop
for (const fruit of fruits) {
console.log(fruit);
}
// forEach
fruits.forEach(fruit => {
console.log(`I love ${fruit}!`);
});
// Convert to Array
const fruitArray = [...fruits];
console.log(fruitArray);
// ["apple", "banana", "cherry"]
Getting Keys and Values
// In Sets, keys and values are the same thing!
for (const item of fruits.keys()) {
console.log(item);
}
for (const item of fruits.values()) {
console.log(item); // Same result!
}
โจ Removing Duplicates with Set โ The Magic Trick!
Hereโs the superpower everyone loves about Sets!
Remove Duplicates from Array
// Messy array with duplicates
const messy = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
// One-line magic! โจ
const clean = [...new Set(messy)];
console.log(clean); // [1, 2, 3, 4]
How It Works
graph TD A["Array with duplicates"] --> B["Create Set from Array"] B --> C["Set removes duplicates automatically"] C --> D["Spread back into Array"] D --> E["Clean unique array!"]
More Examples
// Remove duplicate words
const words = ["hi", "hello", "hi", "hey", "hello"];
const uniqueWords = [...new Set(words)];
// ["hi", "hello", "hey"]
// Remove duplicate letters
const letters = "mississippi".split("");
const uniqueLetters = [...new Set(letters)].join("");
// "misp"
Real-World Use Cases
// Get unique tags from posts
const allTags = ["js", "web", "js", "css", "web"];
const uniqueTags = [...new Set(allTags)];
// Find unique visitors
const visits = ["user1", "user2", "user1", "user3"];
const uniqueVisitors = new Set(visits).size; // 3
๐ฎ Quick Comparison: Map vs Set
| Feature | Map | Set |
|---|---|---|
| Stores | Key-value pairs | Single values |
| Duplicates | Keys must be unique | Values must be unique |
| Access | By key | Check existence |
| Use case | Dictionary/lookup | Unique collection |
๐ Summary โ Your New Superpowers!
Map โ The Labeled Drawer System
- Stores key-value pairs
- Keys can be any type
- Use
.set(),.get(),.has(),.delete() - Perfect for lookups and dictionaries
Set โ The Duplicate Destroyer
- Stores unique values only
- Automatically removes duplicates
- Use
.add(),.has(),.delete() - Perfect for tracking unique items
The Ultimate Trick
// Clean any array in one line!
const unique = [...new Set(arrayWithDuplicates)];
Now you have two powerful treasure chests in your JavaScript toolkit! ๐
