🔢 Counts the occurrences of items in an array, grouped by a generated key.
Syntax
TypeScript
import { countBy } from '@opentf/std'; countBy<T>( arr: T[] = [], by: ((val: T) => string) | string ): Record<string, number>
Parameters
arr: The source array.by: An iteratee (function or property name) to generate the keys.
Returns
An object with the keys and their respective counts.
Examples
TypeScript
countBy([]) //=> {} countBy([1, 2, 3, 4, 5, 6, 7, 8, 9], (v) => v % 2 === 0 ? 'Even' : 'Odd' ) //=> { Even: 4, Odd: 5 } countBy(['Apple', 'Mango', 'Orange'], 'length') //=> // { // '5': 2, // '6': 1, // } const inventory = [ { name: 'asparagus', type: 'vegetables', qty: 5 }, { name: 'bananas', type: 'fruit', qty: 0 }, { name: 'goat', type: 'meat', qty: 23 }, { name: 'cherries', type: 'fruit', qty: 5 }, { name: 'fish', type: 'meat', qty: 22 }, ]; countBy(inventory, ({ qty }) => (qty === 0 ? 'Out-Of-Stock' : 'In-Stock')) //=> { 'Out-Of-Stock': 1, 'In-Stock': 4 } const letters = ['a', 'b', 'A', 'a', 'B', 'c']; countBy(letters, (l) => l.toLowerCase()) //=> // { // a: 3, // b: 2, // c: 1, // }