Advanced · 12 min
Index data with Maps
Build a lookup once when you need repeated access by identifier.
Create an index
Repeated find() calls may scan the same array many times. Build a Map for repeated ID lookups when the extra memory and setup are worthwhile. Measure real workloads before optimizing.
const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Mina" }];
const byId = new Map(users.map(user => [user.id, user]));
console.log(byId.get(2).name);Output
Mina
Know the key rules
A Map distinguishes number keys from string keys. Setting an existing key replaces its value. Decide how your application should handle duplicate IDs.
const values = new Map();
values.set(1, "First");
values.set(1, "Updated");
values.set("1", "Text key");
console.log(values.size);
console.log(values.get(1));Output
2 Updated
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Build an ID lookup
Index users by their numeric id, then display the name for ID 2.
Use user.id as the Map key.