Grouping Plots With Object.groupBy()
The section reps want a list of the plots in their section. The garden has nine plots in sections A, B and C, and section D’s new raised beds by the gate have no holders yet. In this lesson, you ported the loop in Rosa’s script that groups the plots, then wrote it the JavaScript way.
Here’s her step, with plots holding the nine plot records (each also has its crops, which this step doesn’t read):
from collections import defaultdict
SECTIONS = ("A", "B", "C", "D")
by_section = defaultdict(list)
for p in plots:
by_section[p["section"]].append(p)
for s in SECTIONS:
print(f"{s}: {len(by_section[s])} plots")
- Python prints
A: 3 plots,B: 3 plots,C: 3 plotsandD: 0 plots. - A line-by-line port starts from an empty object literal,
const bySection = {};, the way a dict becomes an object. The loop carries across as afor...ofloop, and.append()becomesbySection[p.section].push(p). - That port stops on the first plot, Ana Lima’s, with
TypeError: Cannot read properties of undefined (reading 'push'), and prints nothing. The trace points at thepushline. - In Python, a plain dict would raise a
KeyErrorthere. Thedefaultdictmade an empty list the first time it saw section A, stored it, and handed it back. Reading a missing key of a JavaScript object givesundefined, with no error, and nothing in JavaScript supplies the empty array, so.push()lands onundefined. A Map’s.get()fails the same way. - The records are already in an array, so you don’t need the loop. Hand the whole array to
Object.groupBy(), with a function that returns each record’s key:Object.groupBy(plots, (p) => p.section). The function works like a key function forsorted(): it gets one record and returns a value. Here, nothing gets sorted: records with the same value land in one group. - When records arrive one at a time instead, you’ll build groups another way later in the course.
- The result is an object of arrays, one for each section that has plots, A, B and C, each keeping the plots in the order the
plotsarray had them. Node’s console marks it[Object: null prototype]: it has no inherited properties, so unlike an empty object literal, it doesn’t answer toconstructor. It’s an object, not an array, so it has no.length, andObject.keys(bySection)lists its sections,[ 'A', 'B', 'C' ]. - Watch out for section D: no plot produced its key, so
bySection.Disundefined, where thedefaultdicthands back an empty list and quietly adds the key. Reading its.lengthwould stop the script, so give each lookup a default with?? []. Map.groupBy()takes the same arguments and gives the same groups as a Map: its.sizeis 3,.get("B")hands back the three B plots, and.get("D")isundefined, so the same default applies. Use the Map form when the keys aren’t strings, since an object turns every key into one, or when Map methods suit what comes next.