I am looking to create a function that can achieve the following:
- Accepts an array of products as input
- Returns a new array of products with a unique
groupId
attribute for each - Products will share the same
groupId
if they have common attributes specified by thegroupIfIdentical
parameter
Here is the basic structure of the function:
function groupProductsBySharedAttributes(
products: Product[],
groupIfIdentical: (keyof Product)[],
initialGroupId: string,
) {
}
Products with matching attributes should be grouped in this way:
export function productsAreIdentical(
prod1: Product,
prod2: Product,
groupIfIdentical: (keyof Product)[],
) {
for (const key of groupIfIdentical) {
if (prod1[key] !== prod2[key]) {
return false
}
return true
}
}
For example:
const prods = [{
country: 'china',
material: 'steel',
sku: 1453
},
{
country: 'china',
material: 'steel',
sku: 4874
},
{
country: 'japan',
material: 'steel',
sku: 4874
},
]
const result = groupProductsBySharedAttributes(prods, ['country', 'material'], 1001)
result = [
{
country: 'china',
material: 'steel',
sku: 1453,
groupId: 1001
},
{
country: 'china',
material: 'steel',
sku: 4874,
groupId: 1001
},
{
country: 'japan',
material: 'steel',
sku: 4874,
groupId: 1002
}
]