Building and Copying Maps of Sets

With the rotation checked, the committee turns to the seed order. It buys seed in bulk, so it needs to know which plots grow each crop before planning next year’s order from this year’s.

Rosa’s Python script keeps the answer in a dict of sets, one set of plot numbers per crop. Here, you’ll build that nested data in JavaScript, copy it safely for next year, and print it in full.

Create Each Set on First Use

In Python, a defaultdict(set) creates each crop’s set the first time the loop touches it:

Language: Python
growers = defaultdict(set)
for p in plots:
    for crop in p["crops"]:
        growers[crop].add(p["plot"])

A JavaScript Map has no default, 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 grouping plots by section without Object.groupBy().

Instead, .getOrInsert(), a recent Map method that Node 26 has and plain objects lack, returns the value stored under the key or stores the default you pass and returns that. Here are the nine plots, with only the fields the seed order reads, and the loop that builds growers:

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.