Store key-value pairs with the Map data structure
Maps are collections of key-value pairs where keys can be any type (not just strings like objects). Perfect for tracking pantry inventory, ingredient quantities, or menu item prices!
๐ก Real-World Example:
Track how much of each ingredient you have: Map { "flour" => 500, "sugar" => 300, "eggs" => 12 }
const pantry = new Map();
pantry.set("flour", 500); // Add key-value pair
pantry.set("sugar", 300);
pantry.set("eggs", 12);
console.log(pantry.size); // 3
console.log(pantry.get("flour")); // 500
console.log(pantry.has("sugar")); // true
console.log(pantry.has("milk")); // false
pantry.set("flour", 450); // Update existing
pantry.delete("eggs"); // Remove key-value pair
pantry.clear(); // Remove all entries
const menu = new Map([
["pasta", 12],
["pizza", 15],
["salad", 8]
]);
for (const [dish, price] of menu) {
console.log(`${dish}: $${price}`);
}
// Maps: Any type as key, easy iteration, size property
// Objects: String keys only, more common, simpler syntax
const map = new Map();
map.set(1, "one"); // Number key OK!
map.set(true, "yes"); // Boolean key OK!
Manage a kitchen pantry using Maps! Add, update, and track ingredient quantities with efficient lookups.
Practice fast lookups with Maps! Search for items and update stock levels efficiently.
Create a pantry inventory system:
Example:
managePantry([["flour", 500], ["sugar", 300]], "flour",
450)
โ { totalItems: 2, flourQuantity: 450 }
๐ก Hints:
new Map(items)
.set() to
update
.size and
.get()
Check if items are in stock and get their quantities:
Example:
checkStock([["eggs", 12], ["milk", 2]], ["eggs", "bread",
"milk"])
โ ["eggs", "milk"] (bread not in stock)
๐ก Hints:
.filter() on
searchItems
map.has(item)