I am trying to merge 2 arrays which might contain some different keys from one array to the other.
The thing is that it is not filtering the already-merged-array as it should. I need it to be with unique values.
These are the 2 arrays:
const arr1 = [
{
id: "1",
title: "My Name"
},
{
id: "2",
title: "Your Name"
},
{
group: [
{
id: "4",
title: "Some Agreement"
},
{
id: "5",
title: "Some Beer"
}
]
}
];
const arr2 = [
{
id: "1",
title: "Company Name",
},
{
id: "2",
title: "A title",
},
{
id: "3",
title: "Question Group 1",
},
{
id: "4",
title: "Confidentiality Agreement",
},
{
id: "5",
title: "Some more",
},
{
id: "6",
title: "Ayo",
}
];
The first array sometimes could contain that key named group which is a mix of 2 or more items of the same type as the objects in the core array ({ id: string, title: string }).
The first array is conformed by the items in the second array.
Right now I need to send all of the items of the arr2 to the arr1 without removing those items from the arr2, but I need to exclude from that merge the existing items/ids which also have to be tested against the items within the group key/array. Do you get it?
This should be the final result of arr1 :
const arr1 = [
{
id: "1",
title: "My Name"
},
{
id: "2",
title: "Your Name"
},
{
group: [
{
id: "4",
title: "Some Agreement"
},
{
id: "5",
title: "Some Beer"
}
]
},
{
id: "3",
title: "Question Group 1",
},
{
id: "6",
title: "Ayo",
}
]
As you see there, the new items must be added to the end of the array, the position should persist.
I created a reproducible example: https://codesandbox.io/s/determined-beaver-r5t6v?file=/src/App.js
And the relevant piece of code:
const handleClick = () => {
setMerge((qs) => {
const merged = [...qs, ...qs2];
const unique = merged.filter((v, i, a) => {
return v.id === a[i].id;
});
return unique;
});
};
I got up to there because I can't even filter the array by unique values based on their id.
The thing is that this function could be developed different. I just need to do not allow repeated items in the arr2, including the ones in the group array.