Count the occurrences of array elements

Tally every distinct value into an object.

JavaScript Version 1.0.0 · MIT · .md

count-the-occurrences-of-array-elements.js
function countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; }

Input & expected output

Input

[
  "delivered",
  "deferred",
  "delivered",
  "bounced"
]

Expected output

{
  "delivered": 2,
  "deferred": 1,
  "bounced": 1
}

The edge case

Input

[
  "__proto__",
  "constructor"
]

Expected output

{
  "__proto__": 1,
  "constructor": 1
}

Know the limits

  • Keys become strings, so 1 and "1" share a count.
  • A null-prototype accumulator keeps "__proto__" and "constructor" as ordinary keys; the original counted them wrongly.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Count the occurrences of array elements from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses a null-prototype accumulator so keys such as __proto__ and constructor are counted as data. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.