CODE
const groupBy = <T extends Object>(data: T[], key: keyof T): Record<string, T[]> => {
return data.reduce((acc: Record<string, T[]>, cur: T) => {
var group = cur[key] as unknown as string;
if (acc[group] === undefined) {
acc[group] = [];
}
acc[group].push(cur);
return acc;
}, {});
};
const groupBy = <T extends Object>(data: T[], key: keyof T): Record<string, T[]> => {
return data.reduce((acc: Record<string, T[]>, cur: T) => {
var group = cur[key] as unknown as string;
if (acc[group] === undefined) {
acc[group] = [];
}
acc[group].push(cur);
return acc;
}, {});
};
HOW TO USE
interface Snippet {
title: string;
category: string;
}
const allSnippets: Snippet[] = [
{ title: "snippet1", category: "React" },
{ title: "snippet2", category: "JavaScript" },
{ title: "snippet3", category: "TypeScript" },
{ title: "snippet4", category: "React" },
{ title: "snippet5", category: "React" },
{ title: "snippet6", category: "JavaScript" },
{ title: "snippet7", category: "TroubleShooting" },
];
console.log(groupBy(allSnippets, "category"));
interface Snippet {
title: string;
category: string;
}
const allSnippets: Snippet[] = [
{ title: "snippet1", category: "React" },
{ title: "snippet2", category: "JavaScript" },
{ title: "snippet3", category: "TypeScript" },
{ title: "snippet4", category: "React" },
{ title: "snippet5", category: "React" },
{ title: "snippet6", category: "JavaScript" },
{ title: "snippet7", category: "TroubleShooting" },
];
console.log(groupBy(allSnippets, "category"));
RESULT
{
"JavaScript": [
{ "title": "snippet2", "category": "JavaScript" },
{ "title": "snippet6", "category": "JavaScript" }
],
"React": [
{ "title": "snippet1", "category": "React" },
{ "title": "snippet4", "category": "React" },
{ "title": "snippet5", "category": "React" }
],
"TroubleShooting": [{ "title": "snippet7", "category": "TroubleShooting" }],
"TypeScript": [{ "title": "snippet3", "category": "TypeScript" }]
}
RESULT
{
"JavaScript": [
{ "title": "snippet2", "category": "JavaScript" },
{ "title": "snippet6", "category": "JavaScript" }
],
"React": [
{ "title": "snippet1", "category": "React" },
{ "title": "snippet4", "category": "React" },
{ "title": "snippet5", "category": "React" }
],
"TroubleShooting": [{ "title": "snippet7", "category": "TroubleShooting" }],
"TypeScript": [{ "title": "snippet3", "category": "TypeScript" }]
}