countBy
Import from @varavel/vdl-plugin-sdk/utils/arrays.
Count the occurrences of each item in an array based on a transformation function.
This function takes an array and a transformation function that converts each item in the array to a key. It then counts the occurrences of each transformed item and returns an object with the transformed items as keys and the counts as values.
Type Parameters
| Type Parameter | Description |
|---|---|
T |
The type of the items in the input array. |
K extends PropertyKey |
The type of keys. |
Parameters
| Parameter | Type | Description |
|---|---|---|
arr |
readonly T[] |
The input array to count occurrences. |
mapper |
(item, index, array) => K |
The transformation function that maps each item, its index, and the array to a key. |
Returns
Record\<K, number>
An object containing the transformed items as keys and the counts as values.
Examples
const array = ['a', 'b', 'c', 'a', 'b', 'a'];
const result = countBy(array, x => x);
// result will be { a: 3, b: 2, c: 1 }