Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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?

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!