Count by the properties of an array of objects

Tally records by the value of one field.

JavaScript Version 1.0.0 · MIT · .md

count-by-the-properties-of-an-array-of-objects.js
function countBy({ values, key }) { return { ...values.reduce((counts, item) => ((counts[item[key]] = (counts[item[key]] || 0) + 1), counts), Object.create(null)) }; }

Input & expected output

Input

{
  "values": [
    {
      "status": "delivered"
    },
    {
      "status": "deferred"
    },
    {
      "status": "delivered"
    }
  ],
  "key": "status"
}

Expected output

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

The edge case

Input

{
  "values": [],
  "key": "status"
}

Expected output

{}

Know the limits

  • Records without the field are counted under "undefined".
  • A null-prototype accumulator keeps special keys as data.

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 by the properties of an array of objects from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses a null-prototype accumulator. 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”.