Patterns as words

Lesson 6 Collections

6 min read · JavaScript · Quiz

group-by, index-by-id, dedupe, zip and partition

What you'll learn

  • Name the five collection shapes: group-by, index-by-id, dedupe, zip and partition
  • Ask the trap question for each shape
  • Spot the quiet data loss: overwritten keys, dropped items and exhausted generators

AI code loves to reshape lists: group them, index them, dedupe them, pair them, split them. Each shape has a one-word name, and a one-word trap.

The idea

Five shapes cover most of it. group-by: one key, a list of items for each key. index-by-id: one key, one item, for fast lookup. dedupe: keep each value once. zip: walk two lists side by side. partition: split one list into two, the items that match and the ones that don't.

Name the shape from what comes out, not from how the loop looks. Then ask the trap question for that shape: what if two items share a key? What counts as the "same" value? What if the two lists have different lengths? What if an item fits neither half?

reshape.js
1const byCustomer = {};2for (const order of orders) {3  if (!byCustomer[order.customerId]) byCustomer[order.customerId] = [];4  byCustomer[order.customerId].push(order);5}67const byId = new Map(orders.map((o) => [o.id, o]));89const cities = [...new Set(customers.map((c) => c.city))];1011const paid = orders.filter((o) => o.paid);12const unpaid = orders.filter((o) => !o.paid);1314const pairs = names.map((name, i) => [name, prices[i]]);
  1. Line 3 Group-by. The first line of the loop makes the list the first time a customer appears. Without it, .push would crash.
  2. Line 7 Index-by-id. One order per id. If two orders share an id, the later one silently wins.
  3. Line 9 Dedupe. A Set keeps each value once, but "same" means the same object for objects, not the same contents.
  4. Line 14 Zip. If prices is shorter than names, the missing prices are quietly undefined.

Take away

  • Five shapes: group-by, index-by-id, dedupe, zip, partition.
  • Name the shape from what comes out, then ask its trap question.
  • Traps: duplicate keys overwrite, "same" has a meaning, lists differ in length, halves must not overlap or leave gaps.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.