File size: 660 Bytes
d9494a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { type StringPropertyKeys } from '@/utils/trim-and-remove-duplicated-whitespaces-from-object-string-properties';
import { isDefined } from '@/utils/validation';

export const fromArrayToValuesByKeyRecord = <T extends object>({
  array,
  key,
}: {
  array: T[];
  key: StringPropertyKeys<T>;
}) => {
  return array.reduce<Record<string, T[]>>((acc, value) => {
    const computedKey = value[key] as string;
    const occurrence = acc[computedKey];

    if (isDefined(occurrence)) {
      return {
        ...acc,
        [computedKey]: [...occurrence, value],
      };
    }

    return {
      ...acc,
      [computedKey]: [value],
    };
  }, {});
};