| 1 | /**
|
|---|
| 2 | * Groups the elements of an array based on a provided key-generating function.
|
|---|
| 3 | *
|
|---|
| 4 | * This function takes an array and a function that generates a key from each element. It returns
|
|---|
| 5 | * an object where the keys are the generated keys and the values are arrays of elements that share
|
|---|
| 6 | * the same key.
|
|---|
| 7 | *
|
|---|
| 8 | * @template T - The type of elements in the array.
|
|---|
| 9 | * @template K - The type of keys.
|
|---|
| 10 | * @param {T[]} arr - The array to group.
|
|---|
| 11 | * @param {(item: T, index: number, array: readonly T[]) => K} getKeyFromItem - A function that generates a key from an element, its index, and the array.
|
|---|
| 12 | * @returns {Record<K, T[]>} An object where each key is associated with an array of elements that
|
|---|
| 13 | * share that key.
|
|---|
| 14 | *
|
|---|
| 15 | * @example
|
|---|
| 16 | * const array = [
|
|---|
| 17 | * { category: 'fruit', name: 'apple' },
|
|---|
| 18 | * { category: 'fruit', name: 'banana' },
|
|---|
| 19 | * { category: 'vegetable', name: 'carrot' }
|
|---|
| 20 | * ];
|
|---|
| 21 | * const result = groupBy(array, item => item.category);
|
|---|
| 22 | * // result will be:
|
|---|
| 23 | * // {
|
|---|
| 24 | * // fruit: [
|
|---|
| 25 | * // { category: 'fruit', name: 'apple' },
|
|---|
| 26 | * // { category: 'fruit', name: 'banana' }
|
|---|
| 27 | * // ],
|
|---|
| 28 | * // vegetable: [
|
|---|
| 29 | * // { category: 'vegetable', name: 'carrot' }
|
|---|
| 30 | * // ]
|
|---|
| 31 | * // }
|
|---|
| 32 | *
|
|---|
| 33 | * @example
|
|---|
| 34 | * // Using index parameter
|
|---|
| 35 | * const items = ['a', 'b', 'c', 'd'];
|
|---|
| 36 | * const result = groupBy(items, (item, index) => index % 2 === 0 ? 'even' : 'odd');
|
|---|
| 37 | * // result will be: { even: ['a', 'c'], odd: ['b', 'd'] }
|
|---|
| 38 | */
|
|---|
| 39 | declare function groupBy<T, K extends PropertyKey>(arr: readonly T[], getKeyFromItem: (item: T, index: number, array: readonly T[]) => K): Record<K, T[]>;
|
|---|
| 40 |
|
|---|
| 41 | export { groupBy };
|
|---|