Count the occurrences of array elements
Tally every distinct value into an object.
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.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.