When an array contains matching IDs, the goal is to merge these objects into one object without affecting the original array. The current code only returns matching objects, but the expected result should combine them as described.
main.ts
const arr = [{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00445450085",
"rxNumber": "14678904"
}]
},
{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00004080085",
"rxNumber": "1459004"
}]
}
},
{
"body": {
"specialtyID": "7908398",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "06789955085",
"rxNumber": "1478604"
}]
}
}
]
const tempArray = arr;
function arrayMatch(temp, arr) {
const finalArray = [];
arr.forEach((element) => {
tempArray.forEach((temp) => {
if (temp.speicaltyID === element.specialtyID) {
temp.rxInfos.forEach((rxInfo) => {
element.rxInfos.push(rxInfo);
});
}
}
finalArray = arr;
});
return finalArray
}
expected output
const arr = [{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00445450085",
"rxNumber": "14678904"
},
{
"drugNdc": "00004080085",
"rxNumber": "1459004"
}
]
},
{
"body": {
"specialtyID": "7908398",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "06789955085",
"rxNumber": "1478604"
}]
}
}
]