I have a dataset like so:
[
{
id: 'abc',
productType: "Nappies"
variants: ['3 Pack of Nappies', 'small']
},
{
id: 'abc',
productType: "Nappies"
variants: ['6 Pack of Nappies', 'small']
},
{
id: 'abc',
productType: "Nappies"
variants: ['12 Pack of Nappies', 'small']
},
{
id: 'abc',
productType: "Nappies"
variants: ['3 Pack of Nappies', 'medium']
},
{
id: 'abc',
productType: "Nappies"
variants: ['6 Pack of Nappies', 'medium']
},
{
id: 'abc',
productType: "Nappies"
variants: ['12 Pack of Nappies', 'medium']
},
{
id: 'def',
productType: "Wipes"
variants: ['3 Pack of Wipes']
},
{
id: 'def',
productType: "Wipes"
variants: ['6 Pack of Wipes']
},
{
id: 'def',
productType: "Wipes"
variants: ['12 Pack of Wipes']
},
]
As you can see, each of the product IDs is repeated across all the variants. I need to reduce the data down so there is only 1 version of each product with the 'X packs of Nappies', eg:
Desired result:
[
{
id: 'abc',
productType: "Nappies"
variants: ['3 Pack of Nappies', 'small']
},
{
id: 'abc',
productType: "Nappies"
variants: ['6 Pack of Nappies', 'small']
},
{
id: 'abc',
productType: "Nappies"
variants: ['12 Pack of Nappies', 'small']
},
{
id: 'def',
productType: "Wipes"
variants: ['3 Pack of Wipes']
},
{
id: 'def',
productType: "Wipes"
variants: ['6 Pack of Wipes']
},
{
id: 'def',
productType: "Wipes"
variants: ['12 Pack of Wipes']
},
]
The secondary variant in each (size, eg 'small'/'medium') is not important. I've tried running a reduce function that runs a filter and returns true if the reduce object's 'variants' property includes any of the active object's 'variant's property but it returns everything.
const RemoveDuplicates = (array) => {
return array.reduce((arr, item) => {
const removed = arr.filter((obj) => {
return obj.selectedOptions.some((i) =>
item.selectedOptions.includes(i)
)
})
return [...removed, item]
}, [])
}