Count by the properties of an array of objects
Tally records by the value of one field.
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.
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.