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 }
Count occurrences safely. A self-contained example using the JavaScript runtime.
Open this example in the interactive library
const counts = new Map();
for (const value of ["a", "b", "a"])
counts.set(value, (counts.get(value) ?? 0) + 1);
console.log(Object.fromEntries(counts));
{ a: 2, b: 1 }