Array
countBy

Counts the items in the given array and groups them by the name provided.

Syntax

import { countBy } from '@opentf/std';
 
countBy<T>(
  arr: T[] = [],
  by: ((val: T) => string) | string
)

Examples

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'))
//=> { OutOfStock: 1, InStock: 4 });
 
const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
countBy(letters, (l) => l.toLowerCase())
//=>
// {
//   a: 3,
//   b: 2,
//   c: 1,
// }

Try