Take the following two arrays:
const array1 = [
{
props: {
type : 'text',
id : 'item1',
name : 'item1',
value : '@item1@',
},
},
{
props: {
type: 'hidden',
id: 'item2',
name: 'item2',
value: '@item2@',
},
}
];
const array2 = [
{
props: {
type: 'hidden',
id: 'item1',
name: 'item1',
value: '@item1@',
},
}
];
What I'm trying to do is concatenate them into a single array, and remove any duplicates based on the id property. However the caveat here is that the object that does NOT have a type of hidden must have presidence.
So I should basically be left with the contents of array1, as the duplicate item from array2 has the type value of hidden, like so:
// Result
[
{
props: {
type : 'text', // Note the type here is "text"
id : 'item1',
name : 'item1',
value : '@item1@',
},
},
{
props: {
type: 'hidden',
id: 'item2',
name: 'item2',
value: '@item2@',
},
}
];
I can easily concatenate them using:
const array = array1.concat(array2);
My idea was to then use a Filter but I'm having a bit of a brain melt. Here is what I have come up with so far:
const concat = (array1, array2) => {
const array = array1.concat(array2);
const ids = [];
// Create array of ID's
for (const i in array1) {
ids.push(array1[i].props.id);
}
return array.filter((obj) => {
if (obj.props.type !== 'hidden' && ids.includes(obj.props.id)) {
return true;
}
return false;
});
};
Would using a Reduce be a better approach here?
Here is a JSFiddle of what I have so far: https://jsfiddle.net/64uprbhn/
type: "hidden"or always keep them? I'm a bit confused because I don't think you mistyped "must have presidence", sounds like you meant to say "must have precedence". But I want to double check.item1)....one of the object's hadtype:hiddenand the other istype:xxx. The one that hastype:hiddenshould be the one to be removed as the duplicate