Sub topic 11
Grouping Strings, Sets, and Other Iterables
This chapter assumes you have already used Object.groupBy and Map.groupBy on arrays, and that you know what an iterable is: an object with a Symbol.iterator method, which for...of and spread syntax can consume. Some familiarity with generator functions (function*) will also help.
Neither grouping method is tied to arrays. Each one accepts any iterable and walks it with the standard iteration protocol, the same way for...of does. This chapter shows what that means for strings, Sets, Maps, generators, and DOM collections. It also covers the edge cases that come from iteration itself: one-shot iterators, infinite sequences, array holes, and cleanup when your callback throws.
How groupBy Consumes Its Input
Both methods follow the same steps. They call the input's Symbol.iterator method, then repeatedly call next() on the resulting iterator. Each value it yields goes to your callback along with a counter that starts at 0. The method never reads length and never uses numeric indexing. Whatever the iterator yields is exactly what ends up in the groups.
The rest of the chapter follows from this loop. The table lists what each common iterable yields to the callback:
| Input | Each element passed to the callback |
|---|---|
| Array | Each slot's value, including `undefined` for holes |
| String | One Unicode code point, as a string |
| Set | Each member, in insertion order |
| Map | A `[key, value]` entry array |
| `map.keys()` / `map.values()` | Just the key or just the value |
| Generator object | Each value it yields |
| Typed array | Each number |
| `NodeList`, `arguments` | Each node or argument |
Grouping Strings
A string is iterable, so you can pass it straight in without splitting it first:
const text = "Hi 2u!";
const byKind = Object.groupBy(text, (ch) => {
if (/[a-z]/i.test(ch)) return "letter";
if (/\d/.test(ch)) return "digit";
if (ch === " ") return "space";
return "other";
});
console.log(byKind.letter); // ["H", "i", "u"]
console.log(byKind.digit); // ["2"]
console.log(byKind.other); // ["!"]Code points, not UTF-16 units
The string iterator yields code points, and that is different from text[i] or split(""). Characters outside the Basic Multilingual Plane, such as most emoji, take up two UTF-16 units but come through as one element:
const s = "a😀b";
console.log(s.length); // 4
const g = Object.groupBy(s, (ch) => (ch.length > 1 ? "astral" : "bmp"));
console.log(g.astral); // ["😀"]
console.log(g.bmp); // ["a", "b"]You get the same result with [...s], but s.split("") would cut the emoji into two lone surrogates. Grouping the string directly gives you the safer behavior without any extra work.
Grouping segmenter output
Intl.Segmenter.prototype.segment returns an iterable of segment objects. That lets you group words, sentences, or graphemes directly:
const segmenter = new Intl.Segmenter("en", { granularity: "word" });
const segments = segmenter.segment("The cat sat on the mat.");
const parts = Object.groupBy(segments, (seg) =>
seg.isWordLike ? "word" : "other"
);
console.log(parts.word.map((seg) => seg.segment));
// ["The", "cat", "sat", "on", "the", "mat"]
console.log(parts.other.length); // 6 (five spaces and the period)The groups hold the segment objects themselves, so seg.index stays available if you need each word's position in the original text.
Grouping Sets
A Set yields its members in insertion order. Duplicates were already removed when the Set was built:
const tags = new Set(["js", "css", "javascript", "html", "js"]);
console.log(tags.size); // 4
const byLength = Map.groupBy(tags, (tag) => tag.length);
console.log(byLength.get(2)); // ["js"]
console.log(byLength.get(10)); // ["javascript"]
console.log([...byLength.keys()]); // [2, 3, 10, 4]The groups are always arrays, even when the input is a Set. If you need Set semantics per group, convert each group afterwards:
const tags = new Set(["js", "css", "javascript", "html"]);
const byLength = Map.groupBy(tags, (tag) => tag.length);
const asSets = new Map(
[...byLength].map(([len, group]) => [len, new Set(group)])
);
console.log(asSets.get(2).has("js")); // trueGrouping Maps and Their Views
Iterating a Map yields [key, value] entries, so your callback receives a two-element array. Destructuring keeps the callback readable:
const scores = new Map([
["ana", 91],
["ben", 72],
["cy", 85],
]);
const byResult = Object.groupBy(scores, ([, score]) =>
score >= 80 ? "pass" : "review"
);
console.log(byResult.pass); // [["ana", 91], ["cy", 85]]
const passing = new Map(byResult.pass);
console.log(passing.get("cy")); // 85Because each group holds entry arrays, you can pass a group straight to new Map(...) to rebuild a smaller Map. If you only care about one side, group scores.keys() or scores.values() instead. Both are iterators too.
Grouping Generators and Iterators
Any generator object can be grouped, so you can group values without building an intermediate array:
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
const byRemainder = Object.groupBy(range(0, 10), (n) => n % 3);
console.log(byRemainder[0]); // [0, 3, 6, 9]
console.log(byRemainder[1]); // [1, 4, 7]
console.log(byRemainder[2]); // [2, 5, 8]Iterators are consumed once
Iterators are stateful. Once groupBy has drained an iterator, a second call receives nothing:
const it = [1, 2, 3].values();
const parity = (n) => (n % 2 ? "odd" : "even");
const first = Object.groupBy(it, parity);
const second = Object.groupBy(it, parity);
console.log(first.odd); // [1, 3]
console.log(Object.keys(second)); // []Arrays, strings, Sets, and Maps are not affected, because they create a fresh iterator each time. Exhausted iterators cause trouble when you store something like map.entries() in a variable and group it twice.
Infinite sequences never finish
groupBy has to reach done: true before it returns. An infinite generator makes it loop forever and keep growing memory. Limit the sequence first:
function* naturals() {
let n = 1;
while (true) yield n++;
}
function* take(iterable, count) {
if (count <= 0) return;
for (const value of iterable) {
yield value;
if (--count === 0) return;
}
}
const firstTen = Object.groupBy(take(naturals(), 10), (n) =>
n % 2 ? "odd" : "even"
);
console.log(firstTen.even); // [2, 4, 6, 8, 10]In runtimes that support iterator helpers (ES2025, Node.js 22+), naturals().take(10) does the same job.
Cleanup when the callback throws
If your callback throws partway through, groupBy closes the iterator by calling its return() method before rethrowing. For generators, that runs any finally block:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log("cleanup ran");
}
}
try {
Object.groupBy(source(), (n) => {
if (n === 2) throw new Error("bad element");
return "x";
});
} catch (err) {
console.log(err.message);
}
// cleanup ran
// bad elementThis means a generator that holds a resource, such as a file handle or a lock, can release it reliably even when grouping fails.
The Index Is an Iteration Counter
The callback's second argument counts the elements yielded so far. It is not a property key of the source. For a Set or a generator, it is simply the position in iteration order. For a Map, it is the entry's position, not the Map key:
const letters = new Set(["x", "y", "z", "w"]);
const halves = Object.groupBy(letters, (_, i) => (i < 2 ? "front" : "back"));
console.log(halves.front); // ["x", "y"]
console.log(halves.back); // ["z", "w"]Edge Cases with Arrays and Array-Likes
Holes become undefined
The array iterator visits every index from 0 to length - 1, so holes in a sparse array reach your callback as undefined. This differs from forEach, map, and reduce, which skip holes:
const sparse = [1, , 3];
const g = Object.groupBy(sparse, (x) => typeof x);
console.log(g.number); // [1, 3]
console.log(g.undefined); // [undefined]If you are replacing a reduce-based helper, this difference can add a group you did not have before.
Array-likes without an iterator throw
Values like arguments, NodeList, and typed arrays are iterable and work directly. A plain object that only has a length property and numeric keys is not iterable, and neither are numbers, null, or undefined. All of these throw a TypeError. Convert array-likes with Array.from first:
const arrayLike = { length: 2, 0: "a", 1: "b" };
try {
Object.groupBy(arrayLike, (x) => x);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const ok = Object.groupBy(Array.from(arrayLike), (x) => x);
console.log(Object.keys(ok)); // ["a", "b"]In a browser, Object.groupBy(document.querySelectorAll("li"), (li) => li.className) works as written, because NodeList implements Symbol.iterator.
Exercise
What does Object.groupBy("aa😀", (ch, i) => String(i)) return, and why are there three keys instead of four?
Show answer
It returns a null-prototype object { "0": ["a"], "1": ["a"], "2": ["😀"] }. The string iterator yields code points, so the emoji (two UTF-16 units, which is why the length is 4) is one element. The counter therefore only reaches 2.
Exercise
A coworker writes const entries = cache.entries(); const a = Map.groupBy(entries, f); const b = Object.groupBy(entries, g); and finds that b is always empty. Explain the cause and give a fix.
Show answer
cache.entries() returns a single iterator, and the first groupBy call drains it to done. The second call gets no elements. Fix it by passing the Map itself (cache) to each call, by calling cache.entries() separately for each one, or by copying once with [...cache.entries()] and reusing the array.
Exercise
Why does Object.groupBy([, "x"], (v) => v ?? "missing") produce a "missing" group, while [, "x"].reduce(...) with similar logic would not see the hole?
Show answer
groupBy reads elements through the array iterator, which yields undefined for every index up to length, holes included. The ?? operator then maps undefined to "missing". reduce checks whether each index exists and skips holes, so its callback never runs for index 0.