Skip to content

Instantly share code, notes, and snippets.

@anurag-roy
Last active December 30, 2021 08:40
Show Gist options
  • Save anurag-roy/ed149f71573fcca31d27b4d5e28a5ade to your computer and use it in GitHub Desktop.
Save anurag-roy/ed149f71573fcca31d27b4d5e28a5ade to your computer and use it in GitHub Desktop.
let input = [{
"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": ""
}
];
function groupByNthOrder<T>(items: T[], keys: (keyof T)[]) {
let output: any = {};
for (let item of items) {
let latest = output;
for (let i = 0; i < keys.length; i++) {
let currentKey = keys[i];
let currentVal = item[currentKey];
let empty = i === (keys.length - 1) ? [] : {};
latest[currentVal] = latest[currentVal] || empty;
if (i === (keys.length - 1)) {
latest[currentVal].push(item);
}
latest = latest[currentVal];
}
}
return output;
}
console.log(groupByNthOrder(input, ['application', 'type']));
// Produces output:
// {
// "APP1": {
// "TYPE1": [{
// "id": "REPORT1",
// "application": "APP1",
// "type": "TYPE1",
// "title": ""
// },
// {
// "id": "REPORT2",
// "application": "APP1",
// "type": "TYPE1",
// "title": ""
// }
// ],
// "TYPE2": [{
// "id": "REPORT3",
// "application": "APP1",
// "type": "TYPE2",
// "title": ""
// }]
// },
// "APP2": {
// "TYPE3": [{
// "id": "REPORT4",
// "application": "APP2",
// "type": "TYPE3",
// "title": ""
// }]
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment