Created
May 2, 2022 23:41
-
-
Save dacre-denny/a86211ea59e54cd03474db0106578888 to your computer and use it in GitHub Desktop.
Typed aggregation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Item { | |
id : string; | |
application : string; | |
type : string; | |
title : string; | |
} | |
type ResultType = { [key: string] : Array<Item> }; | |
var input : Array<Item> = [{ | |
"id": "REPORT1", | |
"application": "APP1", | |
"type": "TYPE1", | |
"title": "" | |
}, | |
{ | |
"id": "REPORT2", | |
"application": "APP1", | |
"type": "TYPE1", | |
"title": "" | |
}, | |
{ | |
"id": "REPORT3", | |
"application": "APP1", | |
"type": "TYPE2", | |
"title": "" | |
}, | |
{ | |
"id": "REPORT4", | |
"application": "APP2", | |
"type": "TYPE3", | |
"title": "" | |
} | |
]; | |
var output = input.reduce((result : ResultType, item : Item ) => { | |
// Get app object corresponding to current item from result (or insert if not present) | |
var app = result[item.application] = result[item.application] || {}; | |
// Get type array corresponding to current item from app object (or insert if not present) | |
var type = app[item.type] = app[item.type] || []; | |
// Add current item to current type array | |
type.push(item); | |
// Return the result object for this iteration | |
return result; | |
}, {} as ResultType); | |
console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment