# Count the occurrences of array elements

Tally every distinct value into an object.

Canonical: https://1loc.dev/array/count-the-occurrences-of-array-elements/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; }
```

## Input

```json
[
  "delivered",
  "deferred",
  "delivered",
  "bounced"
]
```

## Expected output

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

## Edge case

Input:
```json
[
  "__proto__",
  "constructor"
]
```
Output:
```json
{
  "__proto__": 1,
  "constructor": 1
}
```

## 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 lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/count-the-occurrences-of-array-elements.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Uses a null-prototype accumulator so keys such as __proto__ and constructor are counted as data. Original MDX retained as inert source evidence.
