I am trying to merge two or more arrays but its not working as I am wanting.
I have two arrays arrCustomer and arrCustomerDetails. Both arrays have CustomerID as a key but I am wanting all values from arrCustomerDetails with merged in properties from the array arrCustomer. I tried using _merge but its giving my only the count of the arrCustomer.
Example:
const arrCustomer = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" }
];
const arrCustomerDetail = [
{ id: 1, location: "jupiter", group: "C" },
{ id: 1, location: "venus", group: "G" },
{ id: 2, location: "mars", group: "D" }
];
const expecteResult = [
{ id: 1, name: "a", location: "jupiter", group: "C" },
{ id: 1, name: "a", location: "venus", group: "G" },
{ id: 2, name: "b", location: "mars", group: "D" },
{ id: 3, name: "c" location: "", group: "" }
]
This works but its slow:
let combinedData = [];
arrCustomerDetail.map((element) => {
combinedData.push({
...element,
...arrCustomer.find(
(customer) => customer.id=== element.id
),
});
});
arrCustomer.map((customer) => {
if (
combinedData.findIndex(
(detail) => detail.id=== customer.id
) === -1
)
combinedData.push({
...customer,
});
});
Thanks all