CodingLittle
CodingLittle

Reputation: 1857

How to group array items as a specific typescript type?

lets say I have this array:

  const dataUse = [
    { group: 'z', name: 'hello' },
    { group: 'z', name: 'hello2' },
    { group: 'z', name: 'hello3' },
    { group: 'x', name: 'hello1' },
    { group: 'x', name: 'hello2' }
  ];

I want to group it on group and I do so by:

group func:

  const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
    arr.reduce((groups, item) => {
      (groups[key(item)] ||= []).push(item);
      return groups;
    }, {} as Record<K, T[]>);

calling:

  const grouped = groupBy(dataUse, (i) => i.group);

result:

{
x: Array
z: Array
}

Problem:

I need to be able to access the properties and in my case x and z are dynamic and will never have the same name. So I thought that I need to group my data as a specific container type:

type GroupContainer = {
  group: string;
  items: Array<MyListObj>;
};

Desiered output would be:

[
{Group: 'x', items:Array}
{Group: 'z', items:Array}
]

The helper func does turns this into records and Im not sure how to turn it into GroupContainer

How do I accomplish this?

Upvotes: 2

Views: 79

Answers (1)

tenshi
tenshi

Reputation: 26324

Object.entries will give us an array with key-value pairs, so we can just map over them and use them for our object:

Object.entries(grouped).map(([group, items]) => ({ group, items }))

Playground

Upvotes: 1

Related Questions