JavaScript, lesson 13
You met Map in the collections lesson as a lookup table. This lesson shows the patterns that
make Map and its sibling Set so useful: counting, grouping, removing duplicates and
comparing groups of values.
To count how often each value occurs, read the current count (defaulting to 0), add one,
and store it back:
?? is the nullish coalescing operator: it uses the right side when the left side is
null or undefined, which is exactly what get returns for a missing key. Unlike , it
keeps a real .
2 exercises to try what you just read.
||0To report the results in order, turn the map into an array of [key, value] pairs and sort it:
[...counts] spreads the entries; counts.keys(), counts.values() and counts.entries()
give you the pieces separately.
Grouping means collecting the items that share some property into lists. The built-in
Object.groupBy(items, fn) calls fn on each item and uses the returned string as the group
name:
The result is an object with one array per group. Map.groupBy does the same but returns a
Map, which you want when the group keys are numbers or objects, or when you will loop over the
groups in insertion order. You can always group by hand, too:
A Set stores unique values. Adding a value that is already there does nothing:
The quickest way to remove duplicates from an array while keeping the first-seen order is
[...new Set(array)]. Checking has on a set is fast no matter how large it is, while
includes on an array checks each element in turn.
Node.js 24 supports the set methods from recent JavaScript versions. Each returns a new set:
Sets keep insertion order, so the order of results follows the order in which elements were
first added. When output must be in a particular order, sort it: [...result].sort().
Read a piece of text (any number of lines). Split it into words: lower-case everything and
treat any run of characters that are not letters a–z or apostrophes as a separator. Then
print the 3 most common words as WORD COUNT, most frequent first, breaking ties
alphabetically. If there are fewer than 3 different words, print them all. If there are no
words, print nothing.
Sample input:
Sample output:
Hint: text.toLowerCase().split(/[^a-z']+/) splits the text; filter out empty strings.
Two clubs share a building. The first input line lists the members of the chess club, the second line the members of the drama club (names separated by spaces; a line may list a name twice by mistake, and a club may have no members, which is an empty line). Print four lines, each with the names sorted alphabetically and separated by single spaces:
both: ... members of both clubs,chess only: ...,drama only: ...,total: N the number of different people in at least one club.If a list is empty, print the label followed by -, as in both: -.
Sample input:
Sample output:
const votes = ["tea", "coffee", "tea", "juice", "tea"];
const counts = new Map();
for (const v of votes) {
counts.set(v, (counts.get(v) ?? 0) + 1);
}
console.log(counts); // Map(3) { 'tea' => 3, 'coffee' => 1, 'juice' => 1 }const ranked = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
for (const [drink, n] of ranked) console.log(drink, n);const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
const byLetter = Object.groupBy(words, (w) => w[0]);
console.log(byLetter.b); // [ 'banana', 'blueberry' ]const groups = new Map();
for (const w of words) {
const key = w.length;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(w);
}const seen = new Set(["red", "blue"]);
seen.add("red");
console.log(seen.size, seen.has("blue")); // 2 trueconst morning = new Set(["ana", "ben", "cy"]);
const evening = new Set(["ben", "dee"]);
morning.union(evening); // ana, ben, cy, dee
morning.intersection(evening); // ben
morning.difference(evening); // ana, cy
morning.symmetricDifference(evening); // ana, cy, dee
morning.isSubsetOf(evening); // false
morning.isDisjointFrom(new Set(["x"])); // trueThe cat and the hat.
The CAT sat!the 3
cat 2
and 1ana ben cy ana
ben deeboth: ben
chess only: ana cy
drama only: dee
total: 4