Choosing a collection

One task, four answers. A program has a list of test runs, each with a suite name and a result, and it has to count the runs per suite, name the suites in the order they first ran, and look one up by name. The same records are read with an array, with a Map and a Set, and with a plain object, and the three programs print the same report.

The differences are in the code and in the cost, not in the report: the arrays need a search per run, the Map and the Set answer in one step, and the object is the shortest version and the one that needs care with its keys. The last section is a table of the four collections and the reason to pick each of them, which is the whole of this JavaScript part in one page.

With arrays

The array version keeps two arrays in step: one for the suite names and one for their counts, with the same index meaning the same suite. Every run needs a search through the names, and the lookup at the end is another search, which is the shape that a missed value makes dangerous. The program shows both the answer and the failure.

const runs = [ { suite: 'parser', ok: true }, { suite: 'lexer', ok: false }, { suite: 'parser', ok: true }, { suite: 'codegen', ok: true }, { suite: 'lexer', ok: true }, ]; const suites = []; const counts = []; for (const run of runs) { const index = suites.indexOf(run.suite); if (index === -1) { suites.push(run.suite); counts.push(1); } else { counts[index] += 1; } } console.log('two arrays kept in step:', suites.join(','), counts.join(',')); console.log('the count of the parser:', counts[suites.indexOf('parser')]); console.log('the count of a suite that was not run:', counts[suites.indexOf('docs')]);

node arrays.js

two arrays kept in step: parser,lexer,codegen 2,2,1
the count of the parser: 2
the count of a suite that was not run: undefined

The report is right and the two arrays are right, as long as every push to one is paired with a push to the other: the invariant is in the head of the programmer and not in the data. The last line is the cost of the -1 that indexOf returns, since counts[-1] is a property that does not exist and the failure is silent. The next two versions move the pairs into one collection, where the invariant cannot be broken.

With a Map and a Set

A Map holds the count under the suite name, so the name is the key and the number is the value, and a Set holds the names in the order they first appeared. The update is a read and a write of one entry, and the lookup at the end is one get with a default, which is the version to write when the keys come from data.

const runs = [ { suite: 'parser', ok: true }, { suite: 'lexer', ok: false }, { suite: 'parser', ok: true }, { suite: 'codegen', ok: true }, { suite: 'lexer', ok: true }, ]; const counts = new Map(); const suites = new Set(); for (const run of runs) { suites.add(run.suite); counts.set(run.suite, (counts.get(run.suite) ?? 0) + 1); } console.log('the suites in first-seen order:', [...suites].join(',')); console.log('the counts:', JSON.stringify([...counts])); console.log('a lookup with a default:', counts.get('docs') ?? 0); console.log('one more parser run:', counts.set('parser', counts.get('parser') + 1).get('parser')); console.log('the Set still has three:', suites.size);

node mapset.js

the suites in first-seen order: parser,lexer,codegen
the counts: [["parser",2],["lexer",2],["codegen",1]]
a lookup with a default: 0
one more parser run: 3
the Set still has three: 3

No index and no second array: the name is the key of every count, the Set collects the names, and the two cannot drift apart. The default of zero turned a missing suite into a number a report can print. The last two lines count the same work twice from two structures, and the Set did not grow when the parser ran again, because a Set keeps one copy of each value.

With a plain object

The object version is the shortest, and it needs one care: the table has to be made with Object.create(null), because a suite could be called constructor and a literal would answer that name from its prototype. The counts are own keys, the names come out in insertion order, and the record with fixed fields next to the table is what an object is best at.

const runs = [ { suite: 'parser', ok: true }, { suite: 'lexer', ok: false }, { suite: 'parser', ok: true }, { suite: 'codegen', ok: true }, { suite: 'lexer', ok: true }, ]; const counts = Object.create(null); for (const run of runs) { counts[run.suite] = (counts[run.suite] ?? 0) + 1; } console.log('the counts:', JSON.stringify(counts)); console.log('a key that was not set:', counts.docs); console.log('a name the prototype would have taken:', typeof counts.constructor); const summary = { total: runs.length, failed: runs.filter((run) => !run.ok).length }; console.log('a record with fixed fields:', JSON.stringify(summary)); console.log('the counts as pairs:', JSON.stringify(Object.entries(counts)));

node object.js

the counts: {"parser":2,"lexer":2,"codegen":1}
a key that was not set: undefined
a name the prototype would have taken: undefined
a record with fixed fields: {"total":5,"failed":1}
the counts as pairs: [["parser",2],["lexer",2],["codegen",1]]

The counts are a JSON object in one call, which is the reason to choose this version when the counts are sent to a file or an API. The third line is the null prototype doing its job: a name that every object inherits is undefined here, so the table answers for its own keys only. The last two lines are the other member of the pair: a record with known fields is a literal, and a table with keys from data is a null-prototype object or a Map.

Choosing between them

The four collections answer four different questions, and the table puts the answers side by side. The rule of thumb that follows from it: an ordered list of items is an array, a lookup by a key of any type is a Map, a question about membership is a Set, and a record with known fields is an object.

Collection Holds Keys Order Duplicates Lookup Choose it for
Array items by position an index from 0 the order of the items allowed and usual a walk, or indexOf a sequence, a queue, the result of a map or a filter
Map a value per key any value, compared by identity the insertion order one value per key has and get a cache, a count, a lookup by a key from data
Set values the value is the key the insertion order one copy of each has unique values, membership, a union or an intersection
Object fields text, and always text indexes first, then insertion one value per key a property read a record with known fields, JSON, an options object

Two rows of the table deserve a second look. The order of an object is not the order of its keys in general, since a key that looks like an array index comes first and is compared as a number, which is why a table with keys from data is better as a Map. And the lookup of an object is the fastest of the four for a fixed name, because the name is written in the source and the engine can plan for it, while a key that arrives at run time loses that advantage and a Map is the honest choice.

Exercises

  1. Add one more run of the codegen suite to the data in arrays.js. Which of the three lines changes, and which lines of the Map version change with the same data?
  2. Print the failed runs per suite with the Map version. Which suite has a failure, and what does the count look like?
  3. Build the table in object.js with {} instead of Object.create(null) and count a suite named constructor. Which line of the output goes wrong?
  4. Sort the counts of the Map version from the most runs to the least. Which pairs swap places?
  5. Solve the task with an array of suite objects and one find per run. How many searches does the program make for five runs, and why is that more work than the Map?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which collection keeps items in the order they were inserted and allows duplicates?

    Answer

    An array

    An array is a sequence and makes no claim about its values, while a Set and a Map key are unique.

  2. Which collection answers "is this value present" without a walk?

    Answer

    A Set

    The lookup of a Set is what makes membership cheap, while indexOf walks the array.

  3. What does counts[suites.indexOf("docs")] give when the suite was never run?

    Answer

    undefined, because the index is -1

    indexOf reports a missing value with -1, and no array has a property at that name.

  4. What does this program print? const counts = new Map(); for (const w of ["a", "b", "a"]) counts.set(w, (counts.get(w) ?? 0) + 1); console.log(counts.get("a"), counts.get("b"));

    Answer

    2 1

    The default of zero makes the first count one, and the second a gives two.

  5. Why is Object.create(null) safer than {} for a table of keys from data?

    Answer

    A literal inherits names such as constructor, which a lookup would find

    The null prototype removes every inherited name, so a table answers for its own keys only.

  6. What does this program print? const counts = Object.create(null); counts.a = 1; console.log(JSON.stringify(counts));

    Answer

    {"a":1}

    The table has one own key, and JSON.stringify writes the keys of an object as the fields of a JSON object.

  7. What does this program print? const s = new Set(); s.add("a"); s.add("a"); console.log(s.size);

    Answer

    1

    A Set keeps one copy of each value, so the second add changed nothing.

  8. Which collection is the right one for a queue of jobs taken from the front?

    Answer

    An array, with push and shift

    A queue is a sequence with an order, which is what an array holds, and push with shift is the pair of operations.

  9. What does this program print? const m = new Map([["b", 1], ["a", 2]]); console.log([...m.keys()].join(","));

    Answer

    b,a

    A Map keeps the order in which its keys were inserted, so the keys come back as they were given.

  10. A record with known fields such as a total and a count is best kept as what?

    Answer

    A plain object literal

    Known fields are what an object is for: they are named in the source and JSON writes them directly.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev