I'm currently exploring the most efficient method to categorize and analyze products in O(n) to extract valuable insights from different categories.
Here is a snippet of the data I am working with:
[
{
"code": 25754,
"description": "BLUETOOTH USB AUDIO RECEIVER P2 ADAPTER",
"price": 5.0,
"stock": 10,
"category": {
"id": 1,
"name": "Adapters"
}
},
{
"code": 20212,
"description": "HDMI FEMALE TO FEMALE CONNECTOR ADAPTER",
"price": 2.8,
"stock": 20,
"category": {
"id": 2,
"name": "Electronics"
}
},
]
To reverse the association, creating a list of categories with their corresponding products, I have devised the following solution:
function group_by_categories(products) {
const categories = {}
for (const product of products) {
const { category, ...cleanedProduct } = product
categories[category.id] = categories[category.id] || category
categories[category.id].products = categories[category.id].products || []
categories[category.id].products.push(cleanedProduct)
}
return Object.values(categories)
}
// The resulting structure:
[
{ id: 1, name: 'Adapters', products: [ [Object] ] },
{ id: 2, name: 'Electronics', products: [ [Object] ] }
]
However, I am facing challenges in two key areas.
Is this approach optimal for reversing the relationship? How could I replicate this logic in a language like C without object-oriented features?
Once we organize data this way, is it only possible to iterate through categories and products in O(n²)?
Any help or insight would be greatly appreciated, even if you can address just one of these questions. And please pardon any mistakes in my English as I strive to convey my thoughts clearly.