Need help with grouping an array of objects within another array of objects based on id and code. Despite successful grouping by "id", struggling to achieve the same for the inner array of objects grouped by "code". Spent an entire day without any luck, any assistance would be greatly appreciated. Link to the Stackblitz is included.
const result = this.data.reduce((a, c) => {
const found = a.find(e => e.id === c.id);
if (found) found.accessDetails[0].tcode.push(c.tcode);
else a.push({
groupId: c.groupId,
id: c.id, accessDetails: [
{ code: c.code, tcode: [c.tcode] }
]
});
return a;
}, []);
console.log(result);
}
Input:
data = [{groupId: "111", id: "abc", code: "PPL", tcode: "Email"},
{groupId: "111", id: "abc", code: "PPL", tcode: "SMS"},
{groupId: "111", id: "abc", code: "PHL", tcode: "Email"},
{groupId: "111", id: "abc", code: "PHL", tcode: "Mobile"},
{groupId: "222", id: "def", code: "APL", tcode: "Letter"},
{groupId: "222", id: "def", code: "APL", tcode: "SMS"},
{groupId: "222", id: "def", code: "PPL", tcode: "Mobile"},
{groupId: "222", id: "def", code: "PHL", tcode: "Mobile"},
{groupId: "333", id: "ghi", code: "APL", tcode: "Letter"},
{groupId: "333", id: "ghi", code: "PHL", tcode: "SMS"}]
Expected Output:
[
{
"groupId": "111",
"id": "abc",
"accessDetails": [
{
"code": "PPL",
"tcode": [
"Email"
"SMS"
]
},
{
"code": "PPL",
"tcode": [
"Email"
"Mobile"
]
}
]
},
{
"groupId": "222",
"id": "def",
"accessDetails": [
{
"code": "APL",
"tcode": [
"Letter"
"SMS"
]
},
{
"code": "PPL",
"tcode": [
"Mobile"
]
}
{
"code": "PHL",
"tcode": [
"Mobile"
]
}
]
},
{
"groupId": "333",
"id": "ghi",
"accessDetails": [
{
"code": "APL",
"tcode": [
"Letter"
]
},
{
"code": "PHL",
"tcode": [
"Email"
"SMS"
]
}
]
}
]