#C14551. Product Grouping and Sorting
Product Grouping and Sorting
Product Grouping and Sorting
You are given a JSON array of products. Each product contains the following fields: name (a string), price (a floating-point number), quantity (an integer), and category (a string). Your task is to compute the total cost for each product as (total_cost = price \times quantity) and then group products by their category. Within each category, the products should be sorted in ascending order of their price. Finally, output the result as a JSON object where each key is a category and its value is the list of corresponding products (each including the computed total_cost).
inputFormat
The input consists of a single JSON array provided via standard input (stdin). Each element in the array is a JSON object representing a product with the keys: name, price, quantity, and category.
outputFormat
The output should be a JSON object printed to standard output (stdout). The keys are the distinct product categories, and the value for each key is an array of products (each product is a JSON object including the field total_cost) sorted in ascending order by price.## sample
[
{"name": "ProductA", "price": 50.0, "quantity": 2, "category": "Electronics"},
{"name": "ProductB", "price": 20.0, "quantity": 1, "category": "Furniture"},
{"name": "ProductC", "price": 75.0, "quantity": 3, "category": "Electronics"}
]
{
"Electronics": [
{"name": "ProductA", "price": 50.0, "quantity": 2, "category": "Electronics", "total_cost": 100.0},
{"name": "ProductC", "price": 75.0, "quantity": 3, "category": "Electronics", "total_cost": 225.0}
],
"Furniture": [
{"name": "ProductB", "price": 20.0, "quantity": 1, "category": "Furniture", "total_cost": 20.0}
]
}
</p>