Dev HelpersOpen library
← Back

Count occurrences safely

Count occurrences safely. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const counts = new Map();
for (const value of ["a", "b", "a"])
  counts.set(value, (counts.get(value) ?? 0) + 1);
console.log(Object.fromEntries(counts));

Sample output

{ a: 2, b: 1 }