I want to implement a function that does the following:
- Takes an array of products as an argument
- returns a new array of products, each of which has a new
groupId
attribute. - Different products will share the same
groupId
if they share the same common attributes, the attributes being determined bygroupIfIdentical
See function skeleton here:
function groupProductsBySharedAttributes(
products: Product[],
groupIfIdentical: (keyof Product)[],
initialGroupId: string,
) {
}
Products containing identical attributes should be grouped like this:
export function productsAreIdentical(
prod1: Product,
prod2: Product,
groupIfIdentical: (keyof Product)[],
) {
for (const key of groupIfIdentical) {
if (prod1[key] !== prod2[key]) {
return false
}
return true
}
}
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
}
]