OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Maps, sets and counting categories

Choose collections that make membership and dynamic keys explicit.

Lesson 10 of 25 · About 20 minutes · Beginner · English

By the end of this lesson

Build counts with Map and deduplicate with Set.

Before you start

  • Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
  • Complete lesson 9 or be comfortable with its examples.

Three words to know

Map
A collection of key/value entries with explicit lookup methods.
Set
A collection of unique values.
Membership
Whether a particular key or value is present.

1. Count dynamic keys

A Map stores dynamic keys without the inherited-property names of a plain object. get returns undefined for a missing key. Our count values are always numbers, so ?? 0 supplies the initial zero. The nullish operator uses its fallback only for null or undefined.

Count statusesJAVASCRIPT · Node.js · save as lesson.mjs
const counts = new Map();
for (const status of ["open", "closed", "open"]) {
  counts.set(status, (counts.get(status) ?? 0) + 1);
}
for (const status of [...counts.keys()].sort()) {
  console.log(`${status}: ${counts.get(status)}`);
}
What you should see · example output
closed: 1
open: 2

2. Deduplicate deliberately

Set removes repeated primitive values. Insertion order is retained, but sorting before displaying a report can make the chosen ordering explicit. A new object with identical-looking fields is still a different object identity.

Unique language namesJAVASCRIPT · Node.js · save as lesson.mjs
const languages = new Set(["Python", "JavaScript", "Python"]);
console.log(languages.has("JavaScript"));
console.log([...languages].sort().join(", "));
What you should see · example output
true
JavaScript, Python

3. Serialize an explicit representation

JSON.stringify does not automatically encode Map entries or Set values as their intended contents. Convert them to an array or a documented object shape first. Do not let an apparently successful JSON.stringify call silently discard the information you meant to save.

Make the representation visibleJAVASCRIPT · Node.js · save as lesson.mjs
const statuses = new Set(["open", "closed"]);
console.log(JSON.stringify([...statuses]));
What you should see · example output
["open","closed"]

YOUR TURN

A small check before you continue

If the input is empty, what will a new Map count? Why might sorting be useful?

Show a suggested answer

It has no entries. Sorting defines a reproducible display order instead of making a report depend on which category appeared first.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.