Sub topic 11
Grouping Strings, Sets, and Other Iterables
This chapter assumes you already know how to call Object.groupBy and Map.groupBy with a key callback. It also assumes you know what an iterable is: any value that works in a for...of loop. Both methods accept any iterable, so the input does not have to be an array.
Why iterables work
Neither method reads length or numeric indexes. Each one asks the input for an iterator and pulls elements from it one at a time. Each element goes to your callback along with a counter that starts at 0. That counter is the index argument. As a result, the method accepts anything that for...of accepts.
Strings
A string iterates by Unicode code point, not by UTF-16 code unit. This means characters made of two code units, such as most emoji, arrive as a single element.
const result = Object.groupBy("hello", (char, index) =>
index % 2 === 0 ? "even" : "odd"
);
console.log(result.even); // ["h", "l", "o"]
console.log(result.odd); // ["e", "l"]
const widths = Map.groupBy("a😀b", (ch) => ch.length);
console.log(widths.get(1)); // ["a", "b"]
console.log(widths.get(2)); // ["😀"]Sets
A Set gives you each unique value once, in insertion order. Any duplicates were removed before grouping starts.
const tags = new Set(["js", "css", "json", "html", "js"]);
const byLength = Map.groupBy(tags, (tag) => tag.length);
console.log([...byLength.keys()]); // [2, 3, 4]
console.log(byLength.get(4)); // ["json", "html"]Maps
Iterating a Map produces [key, value] pairs, so each element your callback receives is a two-item array. Destructure it to get at the value.
const scores = new Map([
["ana", 92],
["ben", 67],
["cy", 85],
]);
const byResult = Object.groupBy(scores, ([, score]) =>
score >= 80 ? "pass" : "fail"
);
console.log(byResult.pass); // [["ana", 92], ["cy", 85]]
console.log(byResult.fail); // [["ben", 67]]The groups contain the pair arrays themselves. To get only the names, map over a group: byResult.pass.map(([name]) => name).
Generators
A generator works as input too. This lets you group values computed on the fly without building an array first.
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
const numbers = range(1, 7);
const grouped = Object.groupBy(numbers, (n) => (n % 3 === 0 ? "fizz" : "other"));
console.log(grouped.fizz); // [3, 6]
console.log(grouped.other); // [1, 2, 4, 5]
const again = Object.groupBy(numbers, (n) => n);
console.log(Object.keys(again)); // []Array-likes are not iterables
An object with a length property and numeric keys is array-like, but it is not iterable. Passing one to either method throws a TypeError. Convert it with Array.from first.
const arrayLike = { length: 3, 0: "x", 1: "y", 2: "x" };
try {
Object.groupBy(arrayLike, (v) => v);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const fixed = Object.groupBy(Array.from(arrayLike), (v) => v);
console.log(fixed.x); // ["x", "x"]Browser collections such as the NodeList from document.querySelectorAll are iterable, so you can group them directly. For example, Map.groupBy(document.querySelectorAll("li"), (el) => el.className) groups list items by class.
| Input | Element passed to callback |
|---|---|
| Array | Each item |
| String | Each code point |
| Set | Each unique value |
| Map | Each `[key, value]` pair |
| Generator | Each yielded value (once only) |
| Array-like object | Not accepted, throws `TypeError` |
Exercise
What does Object.groupBy(new Set([1, 2, 2, 3, 3, 3]), (n) => (n % 2 ? "odd" : "even")) return?
Show answer
{ odd: [1, 3], even: [2] }. The Set has already removed duplicates, so each value is grouped once, in insertion order.
Exercise
You have const m = new Map([["a", 1], ["b", 2], ["c", 3]]). Write a Map.groupBy call that groups the entries by whether the value is greater than 1, and then get the keys ("a", "b", "c") in the true group.
Show answer
const g = Map.groupBy(m, ([, v]) => v > 1); then g.get(true).map(([k]) => k) returns ["b", "c"].