if array has matching ids change object to one object without effecting original array with below code it returns only matching objects but i want expected result as mentioned
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"
}]
}
}
]
You can try this method to achieve your desired result:
const result = arr.reduce((container, value) => {
const compare = ({ body }) => body.specialtyID === value.body.specialtyID;
const isExists = container.some(compare);
const pushRxInfos = container.map(item => compare(item) ? item.body.rxInfos.push(...value.body.rxInfos) : item);
isExists ? pushRxInfos : container.push(value);
return container;
}, []);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments