HooneyLog

How to Make Array Grouping in Typescript

프로필 이미지

Seunghoon Shin

2022년 7월 29일 12:47

I think this is very useful util function in every projects.

This could be very useful like when you want to filter an array considering time complexity.

Example

const DUMMY = [
  { category: "food", name: "짜장면" },
  { category: "electronic", name: "TV" },
  { category: "food", name: "떡볶이" },
  { category: "food", name: "라면" },
  { category: "electronic", name: "air conditioner" },
  { category: "electronic", name: "labtop" },
  { category: "electronic", name: "computer" },
  { category: "food", name: "soup" },
  { category: "food", name: "hamburger" },
  { category: "food", name: "noodle" },
  { category: "clothes", name: "tshirt" },
];

Let’s assume you want to get objects which has ‘clothes’ category in the DUMMY.

Filter Method

you can use easily ‘filter’ method like below

const clothes = DUMMY.filter(({category})=>category === 'clothes');

Then you will get this data

[{
  "category": "clothes",
  "name": "tshirt"
}]

this is super easy, right?

but you can make it better.

Problem

as you know, ‘filter’ method’s time complexity is O(n). It means the bigger the array, the longer the time would be. This is not that efficiency, because you just want a simple data that has only one object like ‘clothes’ category.

Solution with GroupBy

you can make it better by grouping by ‘category’ in advance and get the datas by accessing an object’s key.

const groupBy = <T extends Record<string,any>>(array:T[],keyForgrouping:keyof T) => {
   return array.reduce<Record<string,T[]>>((group,item)=>{
        const valueForgrouping:string = item[keyForgrouping];
        return {...group,[valueForgrouping]: group[valueForgrouping] ? [...group[valueForgrouping],item] : [item]}
    },{})
}

console.log(groupBy(DUMMY,'category').clothes)

Conclusion

By using the ‘groupBy’ util function and by fetching the data you really need right away, you will avoid unnecessary array traversal.