I have to form an array of object in another array of object based on id. I was able to group the object based the "id" but was not able to group the inside array of object by "code". Please help with this I know its a small fix but I spend whole day still no result. I have also kept the stackblitz link
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"}]
Expexted 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"
]
}
]
}
]