Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Grouping Plots With Object.groupBy()

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):

Language: Python
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 plots and D: 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 a for...of loop, and .append() becomes bySection[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 the push line.
  • In Python, a plain dict would raise a KeyError there. The defaultdict made an empty list the first time it saw section A, stored it, and handed it back. Reading a missing key of a JavaScript object gives undefined, with no error, and nothing in JavaScript supplies the empty array, so .push() lands on undefined. 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 for sorted(): 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 plots array 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 to constructor. It’s an object, not an array, so it has no .length, and Object.keys(bySection) lists its sections, [ 'A', 'B', 'C' ].
  • Watch out for section D: no plot produced its key, so bySection.D is undefined, where the defaultdict hands back an empty list and quietly adds the key. Reading its .length would 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 .size is 3, .get("B") hands back the three B plots, and .get("D") is undefined, 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.

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

00:02 The section reps want a list of the plots in their section. The garden has nine plots in sections A, B and C. Section D’s new raised beds by the gate have no holders yet.

00:15 You’ll port the loop that groups them. Rosa’s Python script builds a defaultdict of lists. Its loop appends each plot to its section’s list.

00:26 Then it prints how many plots each section has, and D gets zero.

00:33 A line-by-line port starts from an empty object, the way a dict becomes an object literal. The loop carries across as a for...of loop. .append() becomes .push(), on the section’s array, read with square brackets.

00:48 The print loop reads each section’s .length.

00:53 Python printed four lines. What does the port print? Your turn: pause the video and predict.

01:05 Run it, and JavaScript stops with a TypeError: Cannot read properties of undefined (reading 'push'). The trace points at the .push() line.

01:16 Nothing was printed: it stopped on the first plot.

01:21 In Python, a plain dict would raise a KeyError here. The defaultdict made an empty list the first time it saw section A, stored it, and handed it back.

01:32 Reading a missing key of a JavaScript object gives undefined, with no error. Nothing in JavaScript supplies the empty array, so .push() lands on undefined.

01:44 A Map’s .get() would fail the same way.

01:48 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.

01:59 The three loop lines fold into one call.

02:03 The function works like a key function for sorted(): it gets one record and returns a value. Here, nothing gets sorted: records with the same value land in one group.

02:14 When records arrive one at a time instead, you’ll build groups another way later in the course.

02:22 Log the result, and you get an object of arrays, one for each section that has plots: A, B and C. Each array keeps the plots in the order the plots array had them.

02:34 Node’s console marks it with null prototype. That means it has no inherited properties, so unlike an empty object literal, it doesn’t answer to constructor.

02:45 It’s an object, not an array, so it has no .length, and Object.keys() lists its sections.

02:54 Watch out for section D. No plot produced its key, so its group is undefined, where the defaultdict hands back an empty list and quietly adds the key.

03:04 Reading its .length would stop the script, so give each lookup a default: ?? and an empty array. Run it, and JavaScript prints Python’s four lines, and D gets zero.

03:19 Every line matches.

03:23 Map.groupBy() takes the same arguments and gives the same groups as a Map. Its .size is 3, and .get("B") hands back the three B plots.

03:34 .get("D") is undefined too, so the same default applies. Reach for 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.

03:49 The rule to keep: when the records are in an array, hand them to Object.groupBy() or Map.groupBy(), with a function that returns each record’s key.

04:00 Use the object for string keys you’ll print or turn into JSON, and the Map for anything else. Give every lookup of a group that might be missing a default.

04:10 Next up: the exercise Prepare the Harvest Show Report. You’ll list how many entries each plot holder made, with no entries for those who made none, and the classes canceled for having fewer than three, including any class nobody entered.

Become a Member to join the conversation.