Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
31 |
Tags
- 알고리즘
- MSA
- NPM
- docker
- html
- 함수형프로그래밍
- vscode
- V8
- nodeJS
- python
- GIT
- ChatGPT
- Linux
- Schema Registry
- stream
- https
- Functional Programming
- nestjs
- javascript
- 자료구조
- 파이썬
- node.js
- Let's Encrypt
- 비주얼 스튜디오 코드
- MSK
- Generics
- Express
- typescript
- Certbot
- ES6
Archives
- Today
- Total
JangBaGeum.gif
[TypeScript] 제네릭을 이용한 객체 배열 Group by 본문
제네릭을 이용한 Group by
const groupBy = <T, K extends keyof T>(array: T[], key: K) => {
let map = new Map<T[K], T[]>();
array.forEach(item => {
let itemKey = item[key];
if (!map.has(itemKey)) {
map.set(itemKey, array.filter(i => i[key] === item[key]));
}
});
return map;
}
위 함수는 제네릭 T의 배열과 T의 key로 소속되어있는 K를 인자로 받는다.
array를 순회하며 Map에 Key가 존재하는지 확인 후, 없다면 키를 생성하고 배열 내에 동일한 키를 가진 항목을 Map에 추가한다.
const items = [
{type: "dog", name: "fred"},
{type: "cat", name: "milo"},
{type: "dog", name: "otis"},
{type: "duck", name: "barry"},
];
const grouped = groupBy(items, "type");
console.log(grouped);
/* OUTPUT:
{
{
key: "dog",
value: [
{type: "dog", name: "fred"},
{type: "dog", name: "otis"},
]
},
{
key: "cat":
value: [
{type: "cat", name: "milo"},
]
},
{
key: "duck",
value: [
{type: "duck", name: "barry"},
]
}
}
*/
반환 값의 Type은 Map이기에 iterable object 반환할 수 있어 forEach 등을 사용해 순회가 가능하다.
grouped.forEach((items, key) => {
console.log(key, items);
});
'ETC > 알고리즘 & 문법' 카테고리의 다른 글
[JavaScript]Date Object에서 Year/Month/Date 얻기 (1) | 2022.11.17 |
---|---|
[JavaScript] ES6 Map() (0) | 2022.11.16 |
[JavaScript] Convert ES6 Iterable to Array (0) | 2022.11.16 |
[FP] 순수 함수와 비 순수 함수 (0) | 2022.10.11 |
[TypeScript] Generics (0) | 2022.07.13 |