Count array items grouped by a function or property key
Dashboards constantly need quick counts: orders per status, errors per HTTP code, users per country. Write a small helper that groups the items of an array by a key and counts how many items fall into each group.
Implement tallyBy(items, iteratee). It returns an object that maps each key to the number of items that produced it.
tallyBy(items, iteratee) // => { [key: string]: number }
iteratee is a function, call it with each item. Its return value is the key.iteratee is a string, it is a property name. The key is item[iteratee]. This also works on primitives, so 'length' reads the length of a string. If the item is null or undefined, the key is undefined (do not throw).String(key). So 1 and '1' share a group, and true, null, and undefined become 'true', 'null', and 'undefined'.'constructor', 'toString', or 'hasOwnProperty'. They must be counted from zero like any other key. (Keys never equal '__proto__'.){}.const orders = [
{ id: 'A1', status: 'shipped' },
{ id: 'A2', status: 'pending' },
{ id: 'A3', status: 'shipped' },
{ id: 'A4', status: 'cancelled' },
];
tallyBy(orders, 'status');
// => { shipped: 2, pending: 1, cancelled: 1 }
tallyBy([404, 500, 404, 201, 503], (code) => `${Math.floor(code / 100)}xx`);
// => { '4xx': 2, '5xx': 2, '2xx': 1 }
tallyBy(['ok', 'hi', 'hey'], 'length');
// => { 2: 2, 3: 1 }
tallyBy([{ team: 'web' }, {}, null], 'team');
// => { web: 1, undefined: 2 }
tallyBy([], 'status');
// => {}
items is an array without holes. Do not mutate it.null, or undefined.