Ad
Arrays

Description

You are given an array of objects and a key. Your task is to implement a function groupByKey that groups the array of objects based on the specified key. The function should return an object where keys are unique values from the specified key, and values are arrays of objects with the same key value.

Example

const actors = [
  { id: 1, name: 'John Doe', profession: 'Actor' },
  { id: 2, name: 'Jane Smith', profession: 'Director' },
  { id: 3, name: 'Bob Johnson', profession: 'Actor' },
  { id: 4, name: 'Alice Brown', profession: 'Producer' },
  { id: 5, name: 'Charlie Green', profession: 'Director' },
];

const result = groupByKey(actors, 'profession');
/*
Expected Output:
{
  'Actor': [
    { id: 1, name: 'John Doe', profession: 'Actor' },
    { id: 3, name: 'Bob Johnson', profession: 'Actor' },
  ],
  'Director': [
    { id: 2, name: 'Jane Smith', profession: 'Director' },
    { id: 5, name: 'Charlie Green', profession: 'Director' },
  ],
  'Producer': [
    { id: 4, name: 'Alice Brown', profession: 'Producer' },
  ],
}
*/
const groupByKey = <T>(arr: T[], key: keyof T): Record<string, T[]> => {
  return arr.reduce((acc, item) => {
    const keyValue = item[key] as string;

    if (!acc[keyValue]) {
      acc[keyValue] = [];
    }

    acc[keyValue].push(item);

    return acc;
  }, {} as Record<string, T[]>);
};

export default groupByKey;