Last active
December 30, 2021 08:40
-
-
Save anurag-roy/ed149f71573fcca31d27b4d5e28a5ade to your computer and use it in GitHub Desktop.
This file contains 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
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