Building and Copying Maps of Sets

The committee buys seed in bulk, so it needs to know which plots grow each crop. Rosa’s Python script keeps that in a defaultdict(set), then deep-copies it to plan next year’s order. In this lesson, you’ll build, copy, and print that nested data in JavaScript.

Build the Seed Order With getOrInsert()

A Map has no default value, so the line-by-line port growers.get(crop).add(p.plot) stops with TypeError: Cannot read properties of undefined (reading 'add'), the same slip as when grouping plots by section. The Map method .getOrInsert() fills the gap:

Python JavaScript
growers = defaultdict(set) const growers = new Map();
growers[crop].add(p["plot"]) growers.getOrInsert(crop, new Set()).add(p.plot);
growers.setdefault(crop, set()) growers.getOrInsert(crop, new Set())

It returns the value already stored under the key, or stores the default you pass and returns that. It’s a recent addition available in Node 26, and plain objects don’t have it. In older code, you’ll see if (!growers.has(crop)) growers.set(crop, new Set()); before growers.get(crop).add(p.plot). Here .getOrInsert() builds the seed order from the nine plots’ crops:

Language: JavaScript
const plots = [
  { plot: 1, crops: new Set(["potatoes", "beans"]) },
  { plot: 2, crops: new Set(["onions", "garlic"]) },
  { plot: 3, crops: new Set(["potatoes", "squash"]) },
  { plot: 4, crops: new Set(["potatoes", "kale"]) },
  { plot: 5, crops: new Set(["beans", "onions"]) },
  { plot: 6, crops: new Set(["squash", "potatoes"]) },
  { plot: 7, crops: new Set(["potatoes", "onions"]) },
  { plot: 8, crops: new Set(["kale", "beans"]) },
  { plot: 9, crops: new Set(["garlic", "squash"]) },
];

const growers = new Map();
for (const p of plots) {
  for (const crop of p.crops) {
    growers.getOrInsert(crop, new Set()).add(p.plot);
  }
}
console.log(growers);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.