SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 10
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 10 of 30

Array questions VI

flatten a nested array (recursion vs flat(Infinity))chunk an arraygroup by a key (Object.groupBy)

These are the notes for JavaScript Coding Questions, episode 10, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three questions you will also meet in real code every week: flatten a nested array (with recursion, with your own stack, and with flat), chunk an array into pieces of a given size, and group items by a key (by hand and with Object.groupBy).

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages. In error messages, the file path is shortened to main.js.

Q1: Flatten a nested array

Problem. A nested array has arrays inside it, maybe many levels deep. Return one flat array with every value, in the same order.

[1, [2, 3], [4, [5, 6]]]   → [1, 2, 3, 4, 5, 6]
[[[1]], [[2, [3]]]]        → [1, 2, 3]
[1, [], [[]], 2]           → [1, 2]

Real life: a gift parcel with a box inside, and another box inside that. You want every item out on the table.

Think out loud

  • We don't know the depth in advance, so no fixed number of loops can be right.
  • Array.isArray(x) tells us whether an item is an array (typeof says "object" for arrays, so it can't).
  • Edge cases: empty arrays inside, three or more levels, and very deep nesting (20,000 levels).

The obvious attempt: one loop

function flatten(arr) {
  const out = [];
  for (const x of arr) {
    if (Array.isArray(x)) out.push(x);
    else out.push(x);
  }
  return out;
}
console.log(flatten([1, [2, 3], [4, [5, 6]]]));
[ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ]

Nothing changed: both branches push x as it is. The inner arrays go in "still closed".

Spread opens only one level

The spread operator ... pushes each item of x separately:

function flatten(arr) {
  const out = [];
  for (const x of arr) {
    if (Array.isArray(x)) out.push(...x);
    else out.push(x);
  }
  return out;
}
console.log(flatten([1, [2, 3], [4, [5, 6]]]));
console.log(flatten([[[1]], [[2, [3]]]]));
[ 1, 2, 3, 4, [ 5, 6 ] ]
[ [ 1 ], [ 2, [ 3 ] ] ]

Why it fails: spread opens exactly one level. If the box we open has another box inside, that box goes on the table closed.

Recursion: open every box the same way

Recursion means a function that calls itself on a smaller piece of the same problem. To unpack a parcel: take each thing out; a plain item goes on the table; another box is opened with the same steps. It always ends because eventually a box has no boxes inside: that stopping point is the base case (here: an item that is not an array).

function flatten(arr) {
  const out = [];
  for (const x of arr) {
    if (Array.isArray(x)) out.push(...flatten(x));
    else out.push(x);
  }
  return out;
}
console.log(flatten([1, [2, 3], [4, [5, 6]]]));
console.log(flatten([[[1]], [[2, [3]]]]));
console.log(flatten([]), flatten([1, [], [[]], 2]));
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3 ]
[] [ 1, 2 ]

Every level is opened; empty inner arrays simply vanish.

Too deep: Maximum call stack size exceeded

function flatten(arr) {
  const out = [];
  for (const x of arr) {
    if (Array.isArray(x)) out.push(...flatten(x));
    else out.push(x);
  }
  return out;
}
let deep = [42];
for (let i = 0; i < 20000; i++) deep = [deep];
console.log(flatten([1, [2, [3, [4]]]]));
console.log(flatten(deep));
[ 1, 2, 3, 4 ]
main.js:3
  for (const x of arr) {
                  ^

RangeError: Maximum call stack size exceeded

Why: every call waits for its inner call to finish. Each waiting call takes a slot on the call stack, the list JavaScript keeps of functions that are still running, and that stack has a size limit. For this function it runs out after a few thousand levels (5,000 worked, 8,000 did not on our machine); 20,000 levels means 20,000 waiting calls.

An explicit stack: a pile of unopened parcels

Don't make JavaScript remember the unopened boxes; remember them yourself. Put every parcel in a pile (a stack: you always take from the top and put new things on top). Take the top one: a box is emptied back onto the pile, an item goes into the output. It is a plain while loop, so there is no call stack to run out of. The top of the pile is the last item, so values come out backwards: reverse once at the end.

function flatten(arr) {
  const stack = [...arr];
  const out = [];
  while (stack.length) {
    const x = stack.pop();
    if (Array.isArray(x)) stack.push(...x);
    else out.push(x);
  }
  return out.reverse();
}
let deep = [42];
for (let i = 0; i < 20000; i++) deep = [deep];
console.log(flatten([1, [2, 3], [4, [5, 6]]]));
console.log(flatten([[[1]], [[2, [3]]]]));
console.log(flatten(deep));
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3 ]
[ 42 ]

Complexity: every value and every inner array is pushed and popped about once: O(n) time (n = values + arrays) and O(n) space. One warning: push(...x) with an inner array of hundreds of thousands of items can throw its own RangeError (episode 5); push items one by one in a loop if that can happen.

The built-in: flat(depth)

const nested = [1, [2, 3], [4, [5, [6]]]];
console.log(nested.flat());
console.log(nested.flat(2));
console.log(nested.flat(Infinity));
let deep = [42];
for (let i = 0; i < 20000; i++) deep = [deep];
console.log(deep.flat(Infinity));
[ 1, 2, 3, 4, [ 5, [ 6 ] ] ]
[ 1, 2, 3, 4, 5, [ 6 ] ]
[ 1, 2, 3, 4, 5, 6 ]
main.js:7
console.log(deep.flat(Infinity));
                 ^

RangeError: Maximum call stack size exceeded
  • flat() means flat(1): one level only. This is the trap.
  • flat(Infinity) opens everything, and is the natural tool in real code.
  • The built-in is recursive too, and fails at extreme depth just like our first version.
  • flat also removes holes in sparse arrays: [1, , 3].flat() gives [ 1, 3 ].

In an interview: write the recursive version, then mention the stack version for extreme depth and flat(Infinity) for everyday code.

Q2: Chunk an array

Problem. Split an array into chunks (smaller arrays) of a given size. The last chunk may be smaller.

chunk([1, 2, 3, 4, 5, 6], 2)     → [[1, 2], [3, 4], [5, 6]]
chunk([1, 2, 3, 4, 5, 6, 7], 3)  → [[1, 2, 3], [4, 5, 6], [7]]
chunk([1, 2], 5)                 → [[1, 2]]
chunk([], 3)                     → []

Real life: a sweet shop packs 7 laddoos into boxes of 3 (two full boxes and one with a single laddoo); a website shows search results 10 per page.

Think out loud

  • The length may not be a multiple of the size: the last box is half full.
  • Size bigger than the array: one small chunk. Empty array: no chunks.
  • Size 0 (or negative, or 2.5) makes no sense and must be refused.

The obvious attempt: count the chunks first

function chunk(arr, size) {
  const out = [];
  const count = Math.floor(arr.length / size);
  for (let c = 0; c < count; c++) {
    out.push(arr.slice(c * size, c * size + size));
  }
  return out;
}
console.log(chunk([1, 2, 3, 4, 5, 6], 2));
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

Why it fails: 7 / 3 is 2.33, and Math.floor makes it 2, so the half-full box is never packed. No error: the 7 silently disappears. (Math.ceil would fix the count, but the step-by-size loop below is simpler and needs no count at all.)

Step by size, and guard the size

Fill a box with the next size items starting where the last box ended, then move size along. slice(i, i + size) stops at the end of the array by itself, so the last box just gets what is left. If size were 0, i += 0 would loop forever, so check it first and throw a RangeError, the built-in error type for "a value outside the allowed range".

function chunk(arr, size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError(`size must be a whole number >= 1, got ${size}`);
  }
  const out = [];
  for (let i = 0; i < arr.length; i += size) {
    out.push(arr.slice(i, i + size));
  }
  return out;
}
console.log(chunk([1, 2, 3, 4, 5, 6], 2));
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
console.log(chunk([1, 2], 5), chunk([], 3));
console.log(chunk([1, 2, 3], 0));
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
[ [ 1, 2 ] ] []
main.js:3
    throw new RangeError(`size must be a whole number >= 1, got ${size}`);
    ^

RangeError: size must be a whole number >= 1, got 0

Complexity: every item is copied into a chunk exactly once: O(n) time, O(n) space for the result.

Q3: Group by a key

Problem. Put items into lists by a key: { key: [items...] }.

orders grouped by city → { Pune: [chai, vada pav], Delhi: [samosa], Jaipur: [lassi] }
[1, 2, 3, 4, 5] by odd/even → { odd: [1, 3, 5], even: [2, 4] }

Real life: a post office sorts letters into pigeonholes, one per city.

Think out loud

  • The first item of a group finds no list yet.
  • Keys come from data, so a key could be any word, even "toString".
  • Empty input should give an empty result.

The obvious attempt: push straight in

const orders = [
  { item: "chai", city: "Pune" },
  { item: "samosa", city: "Delhi" },
  { item: "vada pav", city: "Pune" },
  { item: "lassi", city: "Jaipur" },
];
function groupBy(arr, key) {
  const groups = {};
  for (const x of arr) {
    groups[x[key]].push(x.item);
  }
  return groups;
}
console.log(groupBy(orders, "city"));
main.js:10
    groups[x[key]].push(x.item);
                   ^

TypeError: Cannot read properties of undefined (reading 'push')

Why: groups.Pune doesn't exist yet; reading a missing key gives undefined, and undefined has no push. We dropped a letter into a pigeonhole nobody had made.

Make the pigeonhole on first use: ??=

The nullish assignment a ??= b assigns b only when a is null or undefined. We also pass a key function instead of a field name, so the same code can group by any rule.

const orders = [
  { item: "chai", city: "Pune" },
  { item: "samosa", city: "Delhi" },
  { item: "vada pav", city: "Pune" },
  { item: "lassi", city: "Jaipur" },
];
function groupBy(arr, keyFn) {
  const groups = {};
  for (const x of arr) {
    const k = keyFn(x);
    groups[k] ??= [];
    groups[k].push(x);
  }
  return groups;
}
const byCity = groupBy(orders, o => o.city);
console.log(Object.keys(byCity));
console.log(byCity.Pune.map(o => o.item));
console.log(groupBy([1, 2, 3, 4, 5], n => n % 2 ? "odd" : "even"));
[ 'Pune', 'Delhi', 'Jaipur' ]
[ 'chai', 'vada pav' ]
{ odd: [ 1, 3, 5 ], even: [ 2, 4 ] }

The toString trap

function groupBy(arr, keyFn) {
  const groups = {};
  for (const x of arr) {
    const k = keyFn(x);
    groups[k] ??= [];
    groups[k].push(x);
  }
  return groups;
}
const words = ["constructor", "map", "toString"];
console.log(groupBy(words, w => w));
main.js:6
    groups[k].push(x);
              ^

TypeError: groups[k].push is not a function

Why: {} is not really empty. It inherits from Object.prototype, which already has keys like constructor and toString holding functions. So groups.constructor is not undefined, ??= does nothing, and we call push on a function. With user data (city names, tags, usernames) this is a real bug, and with __proto__ as a key it can even be a security problem (prototype pollution).

Fix: Object.create(null) makes an object with no prototype: truly empty.

function groupBy(arr, keyFn) {
  const groups = Object.create(null);
  for (const x of arr) {
    const k = keyFn(x);
    groups[k] ??= [];
    groups[k].push(x);
  }
  return groups;
}
const words = ["constructor", "map", "toString", "map"];
console.log(groupBy(words, w => w));
console.log(groupBy(["apple", "avocado", "banana"], w => w[0]));
console.log(groupBy([], w => w));
[Object: null prototype] {
  constructor: [ 'constructor' ],
  map: [ 'map', 'map' ],
  toString: [ 'toString' ]
}
[Object: null prototype] { a: [ 'apple', 'avocado' ], b: [ 'banana' ] }
[Object: null prototype] {}

Node prints [Object: null prototype] to tell you what kind of object it is. Complexity: one pass, each key lookup O(1) on average: O(n) time, O(n) space.

The built-ins: Object.groupBy and Map.groupBy (Node 21+)

const orders = [
  { item: "chai", city: "Pune" },
  { item: "samosa", city: "Delhi" },
  { item: "vada pav", city: "Pune" },
];
const byCity = Object.groupBy(orders, o => o.city);
console.log(byCity);
console.log(byCity.Pune.length, byCity.Mumbai);
console.log(Map.groupBy([1, 2, 3, 4, 5], n => n % 2 ? "odd" : "even"));
[Object: null prototype] {
  Pune: [
    { item: 'chai', city: 'Pune' },
    { item: 'vada pav', city: 'Pune' }
  ],
  Delhi: [ { item: 'samosa', city: 'Delhi' } ]
}
2 undefined
Map(2) { 'odd' => [ 1, 3, 5 ], 'even' => [ 2, 4 ] }
  • Object.groupBy returns a null-prototype object: the same choice we made, for the same reason.
  • A missing group (Mumbai) is undefined, not [].
  • Map.groupBy returns a Map: better when keys are not strings (numbers you want to keep as numbers, or objects).

In an interview: write the loop with ??=, mention the prototype trap, then name Object.groupBy.

Complexity summary

Question Approach Time Extra space
Flatten recursion O(n) O(n) output + O(depth) call stack
Flatten explicit stack O(n) O(n)
Flatten flat(Infinity) O(n) O(n), recursive inside
Chunk step by size + slice O(n) O(n)
Group by loop + ??= O(n) O(n)
Group by Object.groupBy / Map.groupBy O(n) O(n)

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
Spread for flattening out.push(...x) [ 1, 2, 3, 4, [ 5, 6 ] ] spread opens one level recursion or a stack
Too much recursion flatten(deep) with 20,000 levels RangeError: Maximum call stack size exceeded one waiting call per level an explicit stack
Default flat() nested.flat() [ 1, 2, 3, 4, [ 5, [ 6 ] ] ] default depth is 1 flat(Infinity)
Counting chunks with floor Math.floor(arr.length / size) [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] last partial chunk dropped for (i = 0; i < n; i += size)
No size check chunk(arr, 0) the loop never ends i += 0 throw a RangeError
Pushing into a missing group groups[k].push(x) TypeError: Cannot read properties of undefined (reading 'push') the list doesn't exist yet groups[k] ??= []
A plain {} for groups const groups = {} TypeError: groups[k].push is not a function inherits toString, constructor Object.create(null) or Map

Mini project: rider trips per city

Orders arrive in nested batches from several apps. Flatten them, group by city, and split each city's orders into rider trips of 2.

// Orders arrive in nested batches from three delivery apps.
const batches = [
  [{ id: 1, item: "chai", city: "Pune" }, [{ id: 2, item: "samosa", city: "Delhi" }]],
  [[{ id: 3, item: "vada pav", city: "Pune" }], { id: 4, item: "lassi", city: "Jaipur" }],
  [{ id: 5, item: "poha", city: "Pune" }, { id: 6, item: "kachori", city: "Jaipur" }, { id: 7, item: "chole", city: "Delhi" }],
];
const orders = batches.flat(Infinity);
const byCity = Object.groupBy(orders, o => o.city);
for (const city of Object.keys(byCity).sort()) {
  const pages = [];
  const list = byCity[city];
  for (let i = 0; i < list.length; i += 2) pages.push(list.slice(i, i + 2));
  console.log(`${city}: ${list.length} orders, ${pages.length} rider trip(s)`);
  pages.forEach((p, n) => console.log(`  trip ${n + 1}: ${p.map(o => o.item).join(", ")}`));
}
Delhi: 2 orders, 1 rider trip(s)
  trip 1: samosa, chole
Jaipur: 2 orders, 1 rider trip(s)
  trip 1: lassi, kachori
Pune: 3 orders, 2 rider trip(s)
  trip 1: chai, vada pav
  trip 2: poha

Extend it: make the trip size a command-line choice, or group by item instead of city.

Your turn: flatten to a given depth (solution)

Problem. Write flattenDepth(arr, depth) that behaves like arr.flat(depth). flattenDepth([1, [2, [3, [4]]]], 2) → [1, 2, 3, [4]].

Solution

Each recursive call gets depth - 1; when depth reaches 0, an inner array is pushed as it is. The default depth is 1, like flat().

function flattenDepth(arr, depth = 1) {
  const out = [];
  for (const x of arr) {
    if (Array.isArray(x) && depth > 0) out.push(...flattenDepth(x, depth - 1));
    else out.push(x);
  }
  return out;
}
const a = [1, [2, [3, [4]]]];
console.log(flattenDepth(a, 2));
console.log(flattenDepth(a), flattenDepth(a, 0));
console.log(flattenDepth(a, Infinity));
console.log(JSON.stringify(flattenDepth(a, 2)) === JSON.stringify(a.flat(2)));
[ 1, 2, 3, [ 4 ] ]
[ 1, 2, [ 3, [ 4 ] ] ] [ 1, [ 2, [ 3, [Array] ] ] ]
[ 1, 2, 3, 4 ]
true

Infinity - 1 is still Infinity, so depth = Infinity flattens everything. ([Array] is just how console.log shortens arrays nested more than two levels deep.) O(n) time.

Practice questions (with solutions)

1. Split an array into parts nearly equal parts (sizes differ by at most 1, bigger parts first).

Solution
function splitInto(arr, parts) {
  const out = [];
  let start = 0;
  for (let p = 0; p < parts; p++) {
    const size = Math.floor(arr.length / parts) + (p < arr.length % parts ? 1 : 0);
    out.push(arr.slice(start, start + size));
    start += size;
  }
  return out;
}
console.log(splitInto([1, 2, 3, 4, 5, 6, 7], 3));
console.log(splitInto([1, 2, 3, 4, 5], 4));
console.log(splitInto([1, 2], 3));
[ [ 1, 2, 3 ], [ 4, 5 ], [ 6, 7 ] ]
[ [ 1, 2 ], [ 3 ], [ 4 ], [ 5 ] ]
[ [ 1 ], [ 2 ], [] ]

The first length % parts parts get one extra item. Unlike chunk, the number of parts is fixed, so a part can be empty.

2. Group words by length with Map.groupBy.

Solution
const words = ["chai", "dal", "roti", "paneer", "aloo", "rice"];
const byLength = Map.groupBy(words, w => w.length);
console.log(byLength);
console.log(byLength.get(4));
Map(3) {
  4 => [ 'chai', 'roti', 'aloo', 'rice' ],
  3 => [ 'dal' ],
  6 => [ 'paneer' ]
}
[ 'chai', 'roti', 'aloo', 'rice' ]

With a Map the keys stay numbers (get(4), not get("4")) and keep insertion order.

3. Count items per group without storing the items.

Solution
function countBy(arr, keyFn) {
  const counts = Object.create(null);
  for (const x of arr) {
    const k = keyFn(x);
    counts[k] = (counts[k] ?? 0) + 1;
  }
  return counts;
}
console.log(countBy(["Pune", "Delhi", "Pune", "Jaipur", "Pune"], c => c));
console.log(countBy([1, 2, 3, 4, 5, 6], n => n % 3));
[Object: null prototype] { Pune: 3, Delhi: 1, Jaipur: 1 }
[Object: null prototype] { '0': 2, '1': 2, '2': 2 }

The same pattern as group by, with a number instead of a list. O(n) time, O(k) space for k groups.

Quick quiz

1. (From the video.) What does this print?

const a = [1, [2, [3, [4]]]];
console.log(a.flat(2));

(A) [ 1, 2, 3, 4 ] (B) [ 1, 2, [ 3, [ 4 ] ] ] (C) [ 1, 2, 3, [ 4 ] ] (D) [ 1, [ 2, 3, 4 ] ]

Answer

(C) [ 1, 2, 3, [ 4 ] ]. flat(2) opens two levels; [4] is at the third level, so it stays wrapped.

2. What does this print?

console.log([[1, 2], [3]].flat());
console.log([1, , 3].flat());
Answer
[ 1, 2, 3 ]
[ 1, 3 ]

One level is enough for the first. flat also removes the hole in a sparse array.

3. Why does groupBy(["toString"], w => w) crash with groups = {} but work with Object.groupBy?

Answer

{} inherits toString from Object.prototype, so groups.toString ??= [] does nothing and push is called on a function. Object.groupBy returns an object created with a null prototype, which has no inherited keys.

Interview questions

  1. Flatten a nested array of any depth. Recursion: push values, recurse into arrays (Array.isArray).
  2. What's the problem with recursion for very deep input? Each level is a waiting call on the call stack; too deep gives RangeError: Maximum call stack size exceeded.
  3. How do you flatten without recursion? An explicit stack: pop, push an array's items back, collect values, reverse at the end.
  4. What does flat() do with no argument? Flattens one level (depth = 1); use flat(Infinity) for everything.
  5. Chunk an array into pieces of size k. for (let i = 0; i < n; i += k) out.push(arr.slice(i, i + k)).
  6. What bug happens if you compute the number of chunks with Math.floor? The last partial chunk is dropped.
  7. Why validate size? size = 0 makes i += size loop forever; throw a RangeError.
  8. Write group by. A key function, groups[k] ??= [], then push. O(n).
  9. Why Object.create(null) for a lookup object? A plain object inherits keys like toString, constructor, __proto__, which collide with data keys.
  10. Object.groupBy vs Map.groupBy? Object: string keys, null prototype. Map: any key type, keeps keys as they are.

Glossary

Term Meaning Example
Nested array An array that contains arrays [1, [2, [3]]]
Flatten Turn a nested array into one flat array [1, [2]] → [1, 2]
Depth How many levels of arrays are inside [1, [2, [3]]] has depth 2
Array.isArray(x) Is x an array? (typeof says "object") Array.isArray([]) → true
Spread (...) Expands an array into separate items out.push(...x)
Recursion A function calling itself on a smaller piece flatten(x) inside flatten
Base case The input where recursion stops a value that is not an array
Call stack JavaScript's list of functions still running grows by one per recursive call
RangeError Error for a value outside the allowed range; also thrown when the call stack overflows Maximum call stack size exceeded
Stack (data structure) Last in, first out: take from the top push / pop
flat(depth) Built-in flatten, default depth 1 arr.flat(Infinity)
Infinity A number bigger than every other number Infinity - 1 === Infinity
Sparse array / hole A missing index in an array [1, , 3]
Chunk A smaller array of consecutive items [4, 5, 6]
slice(start, end) A copy from start up to (not including) end; stops at the array's end [1, 2, 3].slice(2, 5) → [3]
Number.isInteger Is the value a whole number? Number.isInteger(2.5) → false
throw Stop and signal an error throw new RangeError("...")
Group by Collect items into lists by a key { Pune: [...], Delhi: [...] }
Key function A function that returns the key for an item o => o.city
Nullish assignment (??=) Assign only if the left side is null/undefined groups[k] ??= []
Prototype The object another object inherits keys from Object.prototype
Object.create(null) An object with no prototype: truly empty safe lookup tables
Null-prototype object What Object.create(null) and Object.groupBy return [Object: null prototype] {}
Prototype pollution A bug/attack where data keys like __proto__ change shared prototypes why lookup objects use null
Object.groupBy Built-in group by returning a null-prototype object (Node 21+) Object.groupBy(arr, fn)
Map.groupBy Built-in group by returning a Map Map.groupBy(arr, fn)

Summary

  • Flatten: spread opens one level; recursion opens every level the same way. Very deep input overflows the call stack (RangeError: Maximum call stack size exceeded), so use your own stack there. flat() is depth 1; flat(Infinity) opens everything.
  • Chunk: don't compute the count with Math.floor (the last chunk vanishes). Step i by size and slice; refuse a size below 1 with a RangeError.
  • Group by: create each list on first use with ??=, and use Object.create(null) so keys like toString don't collide. Object.groupBy and Map.groupBy do exactly this for you.

Next episode: String questions I: reversing a string (and why emojis break split("")), a palindrome check that ignores case and punctuation, and counting vowels.